<template>
  <div style="background-color: white; width: 100%; height: 100%">
    <div :id="mapId" class="olmap" ref="rootmap" style="width: 100%; height: 100%"></div>
    <div id="movePositionDiv" style="cursor: pointer; pointer-events: none"></div>
    <div id="markerDiv" style="cursor: pointer; pointer-events: none"></div>
    <div id="popDiv" class="ol-popup" v-show="isShowPop">
      <a id="popup-closer" class="ol-popup-closer"></a>
      <div id="popup-title" class="popup-title"></div>
      <div id="popup-content" class="popup-content"></div>
    </div>
    <div v-if="legendImg" id="otherDiv" style="position: absolute; bottom: 20px; right: -160px">
      <img :src="legendImg" style="width: 55%"/>
    </div>
    <div v-if="treeData.length > 0" class="layercontrolDiv">
      <div class="layercontrol" title="图层">
        <div class="ol-control">
          <button type="button" @click="showModalBox">
            <a-icon type="block"/>
          </button>
        </div>

        <transition>
          <div class="modalBox" v-show="visible">
            <a-card size="small">
              <div style="margin-top: 8px; margin-left: 10px" slot="title">
                <span>图层</span>
              </div>
              <a-tree
                  v-model="checkedKeys"
                  checkable
                  :expanded-keys="expandedKeys"
                  :auto-expand-parent="autoExpandParent"
                  :selected-keys="selectedKeys"
                  :tree-data="treeData"
                  @expand="onExpand"
                  @select="onSelect"
                  @check="onCheck"
              />
            </a-card>
          </div>
        </transition>
        <!-- <a-popover title="图层" :maskClosable="false" placement="leftTop" trigger="click">
          <template slot="content">
            <a-tree v-model="checkedKeys" checkable :expanded-keys="expandedKeys" :auto-expand-parent="autoExpandParent"
              :selected-keys="selectedKeys" :tree-data="treeData" @expand="onExpand" @select="onSelect"
              @check="onCheck" />
          </template>
          <a-button type="primary" size="small">
            <img style="width: 15px; margin-bottom: 1px;" :src="tuceng" />
          </a-button>
        </a-popover> -->
      </div>
    </div>
  </div>
</template>

<script>
  import 'ol/ol.css'
  import {Map, View, Feature, Overlay} from 'ol'
  import TileLayer from 'ol/layer/Tile'
  import Vector from 'ol/layer/Vector'
  import OSM from 'ol/source/OSM'
  import TileWMS from 'ol/source/TileWMS'
  import TileWMTS from 'ol/source/WMTS'
  import WMTSTileGrid from 'ol/tilegrid/WMTS'
  import {getWidth, getTopLeft, getCenter} from 'ol/extent'
  import VectorSource from 'ol/source/Vector'
  import ImageWMS from 'ol/source/ImageWMS'
  import GeoJSON from 'ol/format/GeoJSON'
  import XYZ from 'ol/source/XYZ'
  import TileImage from 'ol/source/TileImage'
  import TileGrid from 'ol/tilegrid/TileGrid'
  import {Projection, fromLonLat, transform, get, addProjection, addCoordinateTransforms} from 'ol/proj'
  import {Zoom, ZoomSlider, ScaleLine, OverviewMap, defaults as defaultsControl} from 'ol/control'
  import {Style, Fill, Stroke, Icon, Text, Circle as CircleStyle} from 'ol/style'
  import {Point, Polygon, LineString, Circle, MultiPoint} from 'ol/geom'
  import {Draw, Select, Modify, Snap, UndoRedo, defaults} from 'ol/interaction'

  import axios from 'axios'

  import * as turf from '@turf/turf'
  import ExportExcel from '@/utils/excel/excel'

  import {
    createFeature,
    isLayerExitByLayerId,
    localToFeature,
    localToXY,
    highlightFeature,
    highlightFeatures,
    removeHighlightFeature,
    removeAllHighlightFeature,
    addFeature,
    removeFeature,
  } from '@/utils/mapfunction/drawmapN'
  import {batchUpdateLine} from '@/api/leakage/gisdata'

  import {buffer, booleanPointOnLine} from '@/utils/mapfunction/spatialAnalysis'

  import {getGraph} from '@/utils/mapfunction/graphs'
  import {projzh as MyProjzh} from '@/utils/mapfunction/AMapTileFixTool'

  import localPng from './icon/local.png'
  import localGif from './icon/local.gif'
  import firePng from './icon/fire.png'
  import pointStart from './icon/pointStart.png'
  import pointEnd from './icon/pointEnd.png'
  import valveClosingPlanIcon from './icon/valveClosingPlan.png'
  import defaultIcon from './icon/default.png'
  import tuceng from '@/assets/map-svg/left-layer.svg'

  Array.prototype.indexOf = function (val) {
    for (let i = 0; i < this.length; i++) {
      if (this[i] == val) return i
    }
    return -1
  }

  Array.prototype.remove = function (val) {
    let index = this.indexOf(val)
    if (index > -1) {
      this.splice(index, 1)
    }
  }

  const getParentKey = (key, tree) => {
    let parentKey
    for (let i = 0; i < tree.length; i++) {
      let node = tree[i]
      if (node.children) {
        if (node.children.some((item) => item.key === key)) {
          parentKey = node.key
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children)
        }
      }
    }
    return parentKey
  }

  const STYLE_MODIFY = function () {
    let fill = new Fill({
      color: 'rgba(255,255,255,0.4)'
    });
    let stroke = new Stroke({
      color: 'red',
      width: 1.25
    });
    let styles = [new Style({
      image: new CircleStyle({
        fill: fill,
        stroke: stroke,
        radius: 5
      }),
      fill: fill,
      stroke: stroke
    })];
    return styles
  };

  const STYLE_SELECTED_MODIFY = (function () {
      let styles = {};
      styles['Polygon'] = [new Style({
        fill: new Fill({
          color: [255, 255, 255, 0.5]
        })
      }), new Style({
        stroke: new Stroke({
          color: [255, 255, 255, 1],
          width: 3
        })
      }), new Style({
        stroke: new Stroke({
          color: [255, 0, 0, 1],
          width: 2
        })
      }), new Style({
        image: new CircleStyle({
          radius: 3,
          fill: new Fill({
            color: 'red'
          })
        }),
        geometry: function (feature) {
          let coordinates = [];
          let geo;
          if (feature.getGeometry() instanceof Circle) {
            let geo = feature.getGeometry();
            coordinates = [geo.getCenter(), geo.getLastCoordinate()]
          } else {
            geo = feature.getGeometry();
            coordinates = geo.getCoordinates()[0]
          }
          return new MultiPoint(coordinates)
        }
      })];
      styles['Circle'] = styles['Polygon'];
      styles['MultiPolygon'] = styles['Polygon'];
      styles['LineString'] = [new Style({
        stroke: new Stroke({
          color: [255, 255, 255, 1],
          width: 3
        })
      }), new Style({
        stroke: new Stroke({
          color: [255, 0, 0, 1],
          width: 2
        })
      }), new Style({
        image: new CircleStyle({
          radius: 3,
          fill: new Fill({
            color: 'red'
          })
        }),
        geometry: function (feature) {
          let coordinates = feature.getGeometry().getCoordinates();
          return new MultiPoint(coordinates)
        }
      })];
      styles['MultiLineString'] = styles['LineString'];
      styles['Point'] = [new Style({
        image: new Icon({
          src: 'assets/img/map/move.png',
          scale: 0.5
        }),
        zIndex: 100000
      })];
      styles['MultiPoint'] = styles['Point'];
      styles['GeometryCollection'] = styles['Polygon'].concat(styles['Point']);
      return function (feature) {
        return styles[feature.getGeometry().getType()]
      }
    }
  )();

  export default {
    name: 'OlMapN',
    components: {
      // 'sketch-picker': Sketch,
    },
    props: [
      'mapId',
      'baseMapData',
      'featuresData',
      'pointImgUrlMapData',
      'showOverView',
      'layersData',
      'selectedLayerId',
      'featureShowContentMap',
      'featureShowNameMap',
      'featureIdColorMap',
      'legendImage',
      'lineWidth',
      'fillColor',
      'lineColor',
    ],
    data() {
      return {
        tuceng, // 图层icon
        visible: false,
        //弹窗
        popDiv: null,
        //是否显示弹窗
        isShowPop: false,
        //弹窗内容
        popOverlay: null,
        //标记div
        markerDiv: null,
        //标记内容
        markerOverlay: null,
        //图形算法对象
        graphObj: null,
        ModifyObj: null,
        modifyObj: null,
        selectObj: null,
        modifyFlag: false,
        //描绘要素标志
        isDrawing: false,
        //描绘要素类型
        drawType: '',
        //鼠标移到线段端点的X坐标
        drawedFeatureNodeX: null,
        //鼠标移到线段端点的Y坐标
        drawedFeatureNodeY: null,
        //修正节点偏移的匹配对象
        modifyPointMap: {},
        //线段两端参考点的集合
        lineNodeArr: [],
        //折线切割成线段的标志
        lineStringSlice: true,
        //删除未保存要素的标志
        deleteDrawedFeatureFlag: false,
        //底图数据
        baseMap: {},
        //要素数据
        mapdata: [],
        //要素id类型map
        idTypeMap: {},
        //显示数据映射表
        featureShowContentDict: {},
        //id颜色映射表
        featureIdColorDict: {},
        //显示名称映射表
        featureShowNameDict: {},
        //图例图片
        legendImg: undefined,
        //点图标映射表
        pointImgUrlMap: {},
        //描绘的要素集合
        drawedFeatures: [],
        //高亮图层
        hFeature: null,
        //边框宽度
        strokeWidth: 2,
        //填充颜色
        fillColors: {
          hex: '#3BB973',
          hsl: {
            h: 147,
            s: 0.52,
            l: 0.48,
            a: 0.5,
          },
          hsv: {
            h: 147,
            s: 0.68,
            v: 0.73,
            a: 0.5,
          },
          rgba: {
            r: 59,
            g: 185,
            b: 115,
            a: 0.5,
          },
          a: 0.5,
        },
        //边框颜色
        strokeColors: {
          hex: '#D0021B',
          rgba: {
            r: 208,
            g: 2,
            b: 27,
            a: 0.5,
          },
          a: 0.5,
        },
        //图层控制开始
        expandedKeys: ['0-0-0'],
        autoExpandParent: true,
        checkedKeys: [],
        selectedKeys: [],
        disabledKey: null,
        treeData: [],
        //图层控制结束
        //地图定位开始
        coordinateXY: {
          locationX: '112.03603331379101',
          locationY: '22.928770094079322',
        },
        roadXY: {
          layerData: [],
          layerId: '',
          roadData1: [],
          road1: '',
          road1Opt: null,
          roadData2: [],
          road2: '',
          road2Opt: null,
        },
        searchVague: {
          columns: [
            {
              title: '编号',
              dataIndex: 'id',
              width: '30%',
            },
            {
              title: '名称',
              dataIndex: 'name',
              width: '70%',
            },
          ],
          tableData: [
            {
              key: 0,
              id: 3,
              name: `私立中学`,
            },
            {
              key: 1,
              id: 4,
              name: `楚米中学`,
            },
            {
              key: 2,
              id: 5,
              name: `私立学校`,
            },
            {
              key: 3,
              id: 6,
              name: `私立学校`,
            },
            {
              key: 4,
              id: 7,
              name: `私立学校`,
            },
          ],
        },
        //地图定位结束
        //查询统计开始
        //道路缓冲查询
        roadBuffer: {
          layerData: [],
          layerId: '',
          roadData: [],
          roadId: '',
          roadOpt: null,
          distance: '10',
          type: 'POINT',
          fbuffered: null,
          bufferedRes: [],
          table: {
            localType: '',
            columns: [
              {
                title: '点号',
                dataIndex: 'expNo',
              },
              {
                title: '地址',
                dataIndex: 'address',
              },
              {
                title: '工程号',
                dataIndex: 'pId',
              },
            ],
            tableData: [],
          },
        },
        //管线要素查询
        pipeLineSearch: {
          value: '',
          type: 'LINE',
          field: 'length',
          fieldData: [
            {
              field: 'dS',
              name: '管径',
            },
            {
              field: 'length',
              name: '管线长度',
            },
            {
              field: 'lineWidth',
              name: '管线宽度',
            },
            {
              field: 'sDeep',
              name: '起点埋深',
            },
            {
              field: 'eDeep',
              name: '终点埋深',
            },
          ],
          operator: 'EQ',
          operatorData: [
            {
              id: 'LIKE',
              name: '模糊查询',
            },
            {
              id: 'GT',
              name: '大于',
            },
            {
              id: 'GE',
              name: '大于等于',
            },
            {
              id: 'LT',
              name: '小于',
            },
            {
              id: 'LE',
              name: '小于等于',
            },
            {
              id: 'EQ',
              name: '等于',
            },
            {
              id: 'NE',
              name: '不等于',
            },
          ],
          table: {
            localType: '',
            columns: [
              {
                title: '点号',
                dataIndex: 'expNo',
              },
              {
                title: '地址',
                dataIndex: 'address',
              },
              {
                title: '工程号',
                dataIndex: 'pId',
              },
            ],
            tableData: [],
          },
        },
        //查询统计结束
        //管线长度查询开始
        pipeLineLength: {
          tree: {
            selectedKey: '',
            expandedKeys: ['000'],
            searchValue: '',
            autoExpandParent: true,
            dataList: [],
            gData: [],
          },
          pipeMaterial: {
            map: {},
            plainOptions: [],
            checkedList: [],
            indeterminate: false,
            checkAll: false,
          },
          pipeDiameter: {
            plainOptions: [],
            checkedList: [],
            indeterminate: false,
            checkAll: false,
          },
          exportType: 'report',
          table: {
            totalLength: 0,
            columns: [
              {
                title: '材质',
                dataIndex: 'material',
              },
              {
                title: '管经',
                dataIndex: 'dn',
              },
              {
                title: '长度(M)',
                dataIndex: 'length',
              },
            ],
            tableData: [],
          },
        },
        //管线长度查询结束
        //设施数量查询开始
        devicesCount: {
          tree: {
            selectedKey: '',
            expandedKeys: ['000'],
            searchValue: '',
            autoExpandParent: true,
            dataList: [],
            gData: [],
          },
          devicesType: {
            map: {},
            plainOptions: [],
            checkedList: [],
            indeterminate: false,
            checkAll: false,
          },
          exportType: 'report',
          table: {
            totalNum: 0,
            columns: [
              {
                title: '设施类别',
                dataIndex: 'scode',
              },
              {
                title: '个数',
                dataIndex: 'count',
              },
            ],
            tableData: [],
          },
        },
        //设施数量查询结束
        //关阀预案开始
        valveClosingPlan: {
          flag: false,
          selectFeature: null,
          markedFeature: null,
          valveClosingPlanResultMap: {},
          plainOptions: [],
          checkedList: [],
          indeterminate: false,
          checkAll: false,
          table: {
            columns: [
              {
                title: '点号',
                dataIndex: 'address',
              },
              {
                title: '级别',
                dataIndex: 'level',
              },
              {
                title: '设施名称',
                dataIndex: 'pId1',
              },
              {
                title: '开关状态',
                dataIndex: 'pId2',
              },
              {
                title: '位置',
                dataIndex: 'pId3',
              },
              {
                title: '材质',
                dataIndex: 'pId4',
              },
              {
                title: '规格',
                dataIndex: 'pId5',
              },
              {
                title: '埋深',
                dataIndex: 'pId6',
              },
              {
                title: '建设年代',
                dataIndex: 'pId7',
              },
            ],
            tableData: [],
          },
        },
        //关阀预案结束
        //火灾分析开始
        fireAnalysis: {
          point: null,
          fbuffered: null,
          bufferedRes: [],
          flag: false,
          distance: 100,
          table: {
            columns: [
              {
                title: '点号',
                dataIndex: 'address',
              },
              {
                title: '设施类别',
                dataIndex: 'typeName',
              },
              {
                title: '设施名称',
                dataIndex: 'name',
              },
              {
                title: '开关状态',
                dataIndex: 'pId3',
              },
              {
                title: '位置',
                dataIndex: 'pId4',
              },
              {
                title: '材质',
                dataIndex: 'pId5',
              },
              {
                title: '规格',
                dataIndex: 'pId6',
              },
              {
                title: '埋深',
                dataIndex: 'pId7',
              },
              {
                title: '建设年代',
                dataIndex: 'pId8',
              },
            ],
            tableData: [],
          },
        },
        //火灾分析结束
        //连通性分析开始
        linkAnalysis: {
          startFlag: false,
          startPoint: null,
          endFlag: false,
          endPoint: null,
        },
        //连通性分析结束
        //预警分析开始
        earlyWarningAnalysis: {
          type: 'LINE',
          yearLimit: 'year',
          value: 5,
          table: {
            columns: [
              {
                title: '点号',
                dataIndex: 'expNo',
              },
              {
                title: '地址',
                dataIndex: 'address',
              },
              {
                title: '工程号',
                dataIndex: 'pId',
              },
            ],
            tableData: [],
          },
        },
        //预警分析结束
        //高程差分析开始
        altitudeAnalysis: {
          startFlag: false,
          startPoint: null,
          sPoint: {
            name: '',
            h: '',
            address: '',
          },
          startPointSelectedCallback: undefined,
          endFlag: false,
          endPoint: null,
          ePoint: {
            name: '',
            h: '',
            address: '',
          },
          endPointSelectedCallback: undefined,
          canvas: {},
        },
        //高程差分析结束
        pipeNetworkEditingFeature: {}
      }
    },
    async mounted() {
      //获取图形算法对象
      this.graphObj = getGraph()
      this.initMapContent()
    },
    watch: {
      baseMapData: function (data) {
        this.initMapView(data)
        let mapSource
        if (data.vendor == 'MANUAL') {
          mapSource = this.initBaseMap(data)
        } else if (data.vendor == 'wmts') {
          mapSource = this.initWMTSBaseMap(data)
        } else if (data.vendor == 'BAIDU') {
          mapSource = this.initBaiduBaseMap(data)
        } else if (data.vendor == 'AMAP') {
          mapSource = this.initGaodeBaseMap(data)
        } else if (data.vendor == 'TDT') {
          mapSource = this.initTDTBaseMap(data)
        } else if (data.vendor == 'OSM') {
          mapSource = this.initOSMBaseMap(data)
        }
        if (mapSource) {
          this.initOverviewMap(mapSource)
        }

        this.initMap(data)
      },
      featuresData: function (data) {
        this.mapdata = data
        this.initFeatureData(this.mapdata)
      },
      pointImgUrlMapData: function (val) {
        this.pointImgUrlMap = val
      },
      showOverView: function (flag) {
        if (!flag) {
          this.map.removeControl(this.overviewMap)
        }
      },
      selectedLayerId: function (val) {
        this.removeHighlightFeature()
        // this.disabledKey = val
        this.checkedKeys = val.split(',')
        let treeData = this.treeData
        if (treeData.length > 0 && treeData[0].children) {
          let treeDataChildren = this.treeData[0].children
          if (treeDataChildren.length > 0) {
            treeDataChildren.forEach((element) => {
              if (element.key === val) {
                element.disabled = true
              } else {
                element.disabled = false
              }
            })
          }
        }
        this.treeData = treeData
      },
      layersData: function (val) {
        this.removeHighlightFeature()
        let valStr = JSON.stringify(val).replace(/null/g, '""')
        //处理图层控制数据
        let layerControlData = JSON.parse(valStr)
        layerControlData.forEach((element) => {
          if (element.key === this.disabledKey || element.layerCategory === 'BASE') {
            element.disabled = true
            this.checkedKeys = this.checkedKeys.concat([element.key])
          } else {
            element.disabled = false
          }
        })
        this.treeData = [
          {
            title: '所有图层',
            key: '0-0-0',
            children: layerControlData,
          },
        ]
      },
      featureShowContentMap: function (data) {
        this.featureShowContentDict = data
        this.initFeatureData(this.mapdata)
      },
      featureIdColorMap: function (data) {
        this.featureIdColorDict = data
        this.initFeatureData(this.mapdata)
      },
      featureShowNameMap: function (data) {
        this.featureShowNameDict = data
        this.initFeatureData(this.mapdata)
      },
      legendImage: function (data) {
        this.legendImg = data
      },
      lineWidth: function (val) {
        this.strokeWidth = val
      },
      fillColor: function (val) {
        this.fillColors = val
      },
      lineColor: function (val) {
        this.strokeColors = val
      },
    },
    methods: {
      //初始化地图容器
      initMapContent() {
        let map = (this.map = new Map({
          target: this.mapId,
          interactions: new defaults({
            doubleClickZoom: false, //屏蔽双击放大事件
          }),
        }))
        let zoom = new Zoom()
        map.addControl(zoom)

        let zoomSlider = new ZoomSlider()
        map.addControl(zoomSlider)

        let scaleLine = new ScaleLine()
        map.addControl(scaleLine)

        // map.removeControl()
      },
      //初始化底图视角
      initMapView(baseMapData) {
        let mapCenter = JSON.parse('[' + baseMapData.center + ']')
        if (baseMapData.projection != 'EPSG:4326') {
          this.isTransform = true
          mapCenter = transform(mapCenter, 'EPSG:4326', baseMapData.projection)
        }
        let view = new View({
          center: mapCenter,
          zoom: parseInt(baseMapData.zoom),
          minZoom: parseInt(baseMapData.minZoom),
          maxZoom: parseInt(baseMapData.maxZoom),
          projection: baseMapData.projection || 'EPSG:4326',
        })
        this.map.setView(view)
      },
      //初始化底图
      initBaseMap(baseMapData) {
        let tileWMS = new TileWMS({
          url: baseMapData.url,
          params: {
            FORMAT: baseMapData.format,
            LAYERS: baseMapData.layers,
            TILED: true,
          },
          transition: 0,
        })

        //地图底图
        let wmsLayer = new TileLayer({
          source: tileWMS,
        })
        wmsLayer.layerId = 'wmsLayer'
        this.map.addLayer(wmsLayer)

        return tileWMS
      },
      initWMTSBaseMap(baseMapData) {
        const matrixSet = baseMapData.projection
        const projection = get(baseMapData.projection)
        const projectionExtent = projection.getExtent()
        const size = getWidth(projectionExtent) / 256
        let resolutions = new Array(22)
        let matrixIds = new Array(22)
        for (let z = 1; z < 23; z += 1) {
          resolutions[z] = size / 2 ** z
          matrixIds[z] = `${matrixSet}:${z}`
        }
        if (matrixSet == 'EPSG:4326') {
          resolutions = [
            0.001373291015625,
            6.866455078125e-4,
            3.4332275390625e-4,
            1.71661376953125e-4,
            8.58306884765625e-5,
            4.291534423828125e-5,
            2.1457672119140625e-5,
            1.0728836059570312e-5,
            5.364418029785156e-6,
          ]
          matrixIds = [
            'EPSG:4326:9',
            'EPSG:4326:10',
            'EPSG:4326:11',
            'EPSG:4326:12',
            'EPSG:4326:13',
            'EPSG:4326:14',
            'EPSG:4326:15',
            'EPSG:4326:16',
            'EPSG:4326:17',
          ]
        }
        let tileWMTS = new TileWMTS({
          url: baseMapData.url,
          layer: baseMapData.layers,
          matrixSet: matrixSet,
          format: 'image/png',
          projection: baseMapData.projection,
          tileGrid: new WMTSTileGrid({
            origin: getTopLeft(projectionExtent),
            resolutions: resolutions,
            matrixIds: matrixIds,
          }),
        })

        //地图底图
        let wmtsLayer = new TileLayer({
          source: tileWMTS,
        })
        wmtsLayer.layerId = 'wmtsLayer'
        this.map.addLayer(wmtsLayer)

        return tileWMTS
      },
      //初始化百度地图底图
      initBaiduBaseMap(baseMapData) {
        // 对百度地图瓦片进行纠偏------BEGIN
        const projzh = require('projzh');
        let bd09Extent = [-20037726.37, -12474104.17, 20037726.37, 12474104.17];
        let baiduMercator = new Projection({
          code: "baidu",
          extent: bd09Extent,
          units: "m"
        });
        addProjection(baiduMercator);
        addCoordinateTransforms("EPSG:4326", baiduMercator, projzh.ll2bmerc, projzh.bmerc2ll);
        addCoordinateTransforms("EPSG:3857", baiduMercator, projzh.smerc2bmerc, projzh.bmerc2smerc);
        // 对百度地图瓦片进行纠偏------END

        let bmercResolutions = new Array(19);
        for (let i = 0; i < 19; ++i) {
          bmercResolutions[i] = Math.pow(2, 18 - i);
        }

        let urls = [0, 1, 2, 3].map(function (sub) {
          return (
            "http://maponline" +
            sub +
            ".bdimg.com/tile/?qt=vtile&x={x}&y={y}&z={z}&styles=pl&scaler=1&udt=20191119"
          );
        });

        let baiduSource = new XYZ({
          projection: "baidu",
          maxZoom: 18,
          tileUrlFunction: function (tileCoord) {
            let x = tileCoord[1];
            let y = -tileCoord[2] - 1;
            let z = tileCoord[0];
            let hash = (x << z) + y;
            let index = hash % urls.length;
            index = index < 0 ? index + urls.length : index;
            if (x < 0) {
              x = "M" + -x;
            }
            if (y < 0) {
              y = "M" + -y;
            }
            return urls[index].replace("{x}", x).replace("{y}", y).replace("{z}", z);
          },
          tileGrid: new TileGrid({
            resolutions: bmercResolutions,
            origin: [0, 0]
          })
        })

        let baiduMapLayer = new TileLayer({
          source: baiduSource,
          // visible: false,
        })
        this.map.addLayer(baiduMapLayer)
        return baiduSource
      },
      //初始化高德地图底图
      initGaodeBaseMap(baseMapData) {
        // 对高德地图瓦片进行纠偏------BEGIN
        const gcj02Extent = [-20037508.342789244, -20037508.342789244, 20037508.342789244, 20037508.342789244];
        const gcjMecator = new Projection({
          code: "GCJ-02",
          extent: gcj02Extent,
          units: "m"
        });

        addProjection(gcjMecator);
        addCoordinateTransforms("EPSG:4326", gcjMecator, MyProjzh.ll2gmerc, MyProjzh.gmerc2ll);
        addCoordinateTransforms("EPSG:3857", gcjMecator, MyProjzh.smerc2gmerc, MyProjzh.gmerc2smerc);
        // 对高德地图瓦片进行纠偏------END

        let gaodeSource = new XYZ({
          projection: "GCJ-02",
          url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}'
        })

        let gaodeLayer = new TileLayer({
          source: gaodeSource,
        })
        this.map.addLayer(gaodeLayer)

        //鹰眼
        // let overviewMap = new OverviewMap({
        //   layers: [
        //     new TileLayer({
        //       source: gaodeSource,
        //     }),
        //   ],
        //   collapsed: false,
        // })
        // this.map.addControl(overviewMap)
        return gaodeSource
      },
      //初始化天地图底图
      initTDTBaseMap(baseMapData) {
        let tdtSource = new XYZ({
          url: 'http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=49ea1deec0ffd88ef13a3f69987e9a63',
        })
        let tdtSourceAnnotation = new XYZ({
          url: 'http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=49ea1deec0ffd88ef13a3f69987e9a63',
        })
        let tdtLayer = new TileLayer({
          source: tdtSource,
        })
        let tdtLayerAnnotation = new TileLayer({
          source: tdtSourceAnnotation,
        })
        this.map.addLayer(tdtLayer)
        this.map.addLayer(tdtLayerAnnotation)

        //鹰眼
        // let overviewMap = new OverviewMap({
        //   layers: [
        //     new TileLayer({
        //       source: tdtSource,
        //     }),
        //   ],
        //   collapsed: false,
        // })
        // this.map.addControl(overviewMap)

        return tdtSource
      },
      initOSMBaseMap(baseMapData) {
        let osmSource = new OSM()
        let osmLayer = new TileLayer({
          source: osmSource,
        })
        this.map.addLayer(osmLayer)

        //鹰眼
        // let overviewMap = new OverviewMap({
        //   layers: [
        //     new TileLayer({
        //       source: osmSource,
        //     }),
        //   ],
        //   collapsed: false,
        // })
        // this.map.addControl(overviewMap)

        return osmSource
      },
      //初始化鹰眼
      initOverviewMap(layerSource) {
        if (this.showOverView != undefined && !this.showOverView) {
          return
        }
        //鹰眼
        // this.overviewMap = new OverviewMap({
        //   layers: [
        //     new TileLayer({
        //       source: layerSource,
        //     }),
        //   ],
        //   collapsed: false,
        // })
        // this.map.addControl(this.overviewMap)
      },
      //初始化地图
      initMap(baseMapData) {
        const that = this
        let map = this.map

        //实例化polygon的矢量层
        let polygonVector = (this.polygonVector = new Vector({
          //数据源
          source: new VectorSource(),
        }))
        polygonVector.layerId = 'polygonVector'
        map.addLayer(polygonVector)

        //实例化linestring的矢量层
        let lineVector = (this.lineVector = new Vector({
          //数据源
          source: new VectorSource(),
        }))
        lineVector.layerId = 'lineVector'
        map.addLayer(lineVector)

        //实例化pointec的矢量层
        let pointVector = (this.pointVector = new Vector({
          //数据源
          source: new VectorSource({
            wrapX: false,
          }),
        }))
        pointVector.layerId = 'pointVector'
        map.addLayer(pointVector)

        //初始化绘制点线面的图层
        let drawVector = (this.drawVector = new Vector({
          //数据源
          source: new VectorSource({
            wrapX: false,
          }),
        }))
        drawVector.layerId = 'drawVector'
        map.addLayer(drawVector)

        //定义修改几何图形的功能控件
        this.ModifyObj = {
          init: function () {
            //初始化一个交互选择控件，并添加到地图容器中
            this.selectObj = new Select()
            map.addInteraction(this.selectObj)
            //初始化一个交互编辑控件，并添加到地图容器中
            this.modifyObj = new Modify({
              features: this.selectObj.getFeatures(), //选中的要素集
            })
            map.addInteraction(this.modifyObj)
            //设置激活状态变更的处理
            this.setEvents()
          },
          setEvents: function () {
            var selectedFeatures = this.selectObj.getFeatures() //选中的要素集
            //添加选中要素变更事件
            this.selectObj.on('change:active', function () {
              //遍历选择要素集，返回当前第一个要素（即移除的要素）
              selectedFeatures.forEach(selectedFeatures.remove, selectedFeatures)
            })
          },
          setActive: function (active) {
            this.selectObj.setActive(active) //激活选择要素控件
            this.modifyObj.setActive(active) //激活修改要素控件
          },
        }
        this.ModifyObj.init() //初始化几何图形修改控件
        this.ModifyObj.setActive(false) //激活几何图形修改控件

        //地图提示窗口
        let movePositionDiv = document.getElementById('movePositionDiv')
        let overlay = new Overlay({
          //设置弹出框的容器
          element: movePositionDiv,
          //是否自动平移，即假如标记在屏幕边缘，弹出时自动平移地图使弹出框完全可见
          // autoPan: true,
          offset: [20, 0], //偏移量，x，y
        })
        //显示overlay
        map.addOverlay(overlay)
        //地图maker窗口
        this.markerDiv = document.getElementById('markerDiv')
        this.markerOverlay = new Overlay({
          //设置弹出框的容器
          element: this.markerDiv,
          positioning: 'center-bottom',
          offset: [-25, -40], //图片偏移量
        })
        //markerOverlay
        map.addOverlay(this.markerOverlay)

        //地图弹窗
        this.popDiv = document.getElementById('popDiv')
        var closer = document.getElementById('popup-closer')
        closer.onclick = this.hidePop
        this.popOverlay = new Overlay({
          //设置弹出框的容器
          element: that.popDiv,
          //是否自动平移，即假如标记在屏幕边缘，弹出时自动平移地图使弹出框完全可见
          // autoPan: true,
          offset: [20, 0], //偏移量，x，y
        })
        map.addOverlay(this.popOverlay)

        map.on(
          'pointermove',
          function (e) {
            map.getTargetElement().style.cursor = 'auto'
            let coodinate = e.coordinate
            let pixel = map.getEventPixel(e.originalEvent)
            let featureArr = []
            map.forEachFeatureAtPixel(pixel, (feature) => {
              if (!feature.isHighlightFeature) {
                featureArr.push(feature)
              }
              // return feature
            })
            let feature = featureArr[0]
            overlay.setPosition(undefined)
            movePositionDiv.innerHTML = ``
            this.drawedFeatureNodeX = null
            this.drawedFeatureNodeY = null
            if (this.valveClosingPlan && this.valveClosingPlan.flag) {
              movePositionDiv.innerHTML = `<div>选择爆管位置</div>`
              overlay.setPosition(coodinate)
            }
            if (this.linkAnalysis && (this.linkAnalysis.startFlag || this.altitudeAnalysis.startFlag)) {
              movePositionDiv.innerHTML = `<div>起点选样</div>`
              overlay.setPosition(coodinate)
            }
            if (this.valveClosingPlan && (this.linkAnalysis.endFlag || this.altitudeAnalysis.endFlag)) {
              movePositionDiv.innerHTML = `<div>终点选样</div>`
              overlay.setPosition(coodinate)
            }
            if (feature) {
              map.getTargetElement().style.cursor = 'pointer'
              if (this.linkAnalysis && (this.linkAnalysis.startFlag || this.altitudeAnalysis.startFlag)) {
                movePositionDiv.innerHTML = `<div>选择起点</div>`
              } else if (this.linkAnalysis && (this.linkAnalysis.endFlag || this.altitudeAnalysis.endFlag)) {
                movePositionDiv.innerHTML = `<div>选择终点</div>`
              } else if (this.deleteDrawedFeatureFlag) {
                for (let i = 0; i < featureArr.length; i++) {
                  if (featureArr[i].isDrawedFeature && featureArr[i].getGeometry().getType() === this.drawType) {
                    movePositionDiv.innerHTML = `<div>点击删除要素</div>`
                  }
                }
              } else if (this.draw && this.isDrawing) {
                if (this.fireAnalysis && this.fireAnalysis.flag) {
                  movePositionDiv.innerHTML = `<div>设定火灾位置</div>`
                } else {
                  movePositionDiv.innerHTML = `<div>描绘要素</div>`
                }

                let drawedFeatureNode
                for (let i = 0; i < featureArr.length; i++) {
                  if (featureArr[i].isDrawedFeatureNode) {
                    drawedFeatureNode = featureArr[i]
                  }
                }
                if (drawedFeatureNode) {
                  let geom = this.getGeom(drawedFeatureNode)
                  if (geom) {
                    geom = JSON.parse(geom)
                  }
                  if (drawedFeatureNode.isDrawedFeatureNode && drawedFeatureNode.isDrawedFeature) {
                    this.drawedFeatureNodeX = geom[0]
                    this.drawedFeatureNodeY = geom[1]
                    movePositionDiv.innerHTML = `<div>管线节点</br>经度：${geom[0]}</br>维度：${geom[1]}</div>`
                  }
                }
              } else if (feature.isDrawedFeature) {
                movePositionDiv.innerHTML = `<div>请先保存要素，再编辑要素</div>`
              } else if (this.toolBarFlag) {
                movePositionDiv.innerHTML = `<div>双击编辑要素</div>`
              }
              if (feature.showContent) {
                movePositionDiv.innerHTML =
                  `<div style='background: #ffffff; padding: 5px 10px;'>` + feature.showContent + `</div>`
              }
              if (this.modifyFlag) {
                movePositionDiv.innerHTML = `<div style='background: #ffffff; padding: 5px 10px;'>编辑要素</div>`
              }
              //设置overlay的显示位置
              overlay.setPosition(coodinate)
            }
          }.bind(this)
        )

        map.on(
          'singleclick',
          function (e) {
            this.hideMaker()
            this.removeHighlightFeature()
            let coodinate = e.coordinate
            let pixel = map.getEventPixel(e.originalEvent)
            let featureArr = []
            map.forEachFeatureAtPixel(pixel, (feature) => {
              if (!feature.isHighlightFeature) {
                featureArr.push(feature)
              }
            })
            let feature = featureArr[0]
            if (this.isDrawing && this.drawType === 'LineString') {
              for (let i = 0; i < featureArr.length; i++) {
                if (featureArr[i].getGeometry().getType() === 'LineString') {
                  if (this.drawedFeatureNodeX != null && this.drawedFeatureNodeY != null) {
                    let geom = JSON.parse(this.getGeom(featureArr[i]))
                    this.modifyPointMap[geom[geom.length - 1][0] || geom[0]] = this.drawedFeatureNodeX
                    this.modifyPointMap[geom[geom.length - 1][1] || geom[1]] = this.drawedFeatureNodeY
                    this.$message.success('节点已衔接')
                    break
                  }
                }
              }
            }
            if (this.deleteDrawedFeatureFlag) {
              for (let i = 0; i < featureArr.length; i++) {
                if (featureArr[i].isDrawedFeature && featureArr[i].getGeometry().getType() === this.drawType) {
                  let p1 = this.drawVector.getSource().getFeatureByUid(featureArr[i].ol_uid + 'p1')
                  let p2 = this.drawVector.getSource().getFeatureByUid(featureArr[i].ol_uid + 'p2')
                  removeFeature(this.drawVector, p1)
                  removeFeature(this.drawVector, p2)
                  removeFeature(this.drawVector, featureArr[i])
                  this.drawedFeatures.remove(featureArr[i])
                  break
                }
              }
              return
            }
            if (feature && !this.isDrawing) {
              let geom = JSON.parse(feature.geom)
              this.highlightFeature(feature, feature.getGeometry().getType())
              //单击要素并回调
              this.$emit('singlelClickMapFeature', feature)
            }

            if (this.valveClosingPlan && this.valveClosingPlan.flag && feature) {
              if (feature.getGeometry().getType() == 'Polygon') {
                this.$message.warn('请选择管点或者管线！')
                return
              }
              if (this.valveClosingPlan.markedFeature != null) {
                removeFeature(this.drawVector, this.valveClosingPlan.markedFeature)
              }
              this.valveClosingPlan.selectFeature = feature
              this.valveClosingPlan.flag = false
              let iconStyle = new Style({
                image: new Icon({
                  anchor: [0.5, 100],
                  anchorXUnits: 'fraction',
                  anchorYUnits: 'pixels',
                  src: valveClosingPlanIcon,
                  scale: 0.15,
                }),
              })
              let valveClosingPlanFeature = new Feature({
                geometry: new Point(e.coordinate),
              })
              valveClosingPlanFeature.geom = e.coordinate
              valveClosingPlanFeature.setStyle(iconStyle)
              this.valveClosingPlan.markedFeature = valveClosingPlanFeature
              addFeature(this.drawVector, valveClosingPlanFeature)
              this.hideMaker()
            }

            if (this.fireAnalysis && this.fireAnalysis.flag) {
              this.fireAnalysis.flag = false
              this.hideMaker()
            }

            if (this.linkAnalysis && this.linkAnalysis.startFlag) {
              for (let i = 0; i < featureArr.length; i++) {
                if (featureArr[i].getGeometry().getType() === 'Point') {
                  if (this.linkAnalysis && this.linkAnalysis.startPoint != null) {
                    removeFeature(this.drawVector, this.linkAnalysis.startPoint)
                  }
                  let startPoint = featureArr[i]
                  this.linkAnalysis.startFlag = false
                  this.$message.success('已选起点')
                  let iconStyle = new Style({
                    image: new Icon({
                      anchor: [0.5, 160],
                      anchorXUnits: 'fraction',
                      anchorYUnits: 'pixels',
                      src: pointStart,
                      scale: 0.3,
                    }),
                  })
                  let startFeature = new Feature({
                    geometry: new Point(JSON.parse(startPoint.geom)),
                  })
                  startFeature.name = startPoint.name
                  startFeature.geom = startPoint.geom
                  startFeature.setStyle(iconStyle)
                  this.linkAnalysis.startPoint = startFeature
                  this.$parent.setLinkStartPoint(startFeature)
                  addFeature(this.drawVector, startFeature)
                  this.hideMaker()
                }
              }
            }
            if (this.linkAnalysis && this.linkAnalysis.endFlag) {
              for (let i = 0; i < featureArr.length; i++) {
                if (featureArr[i].getGeometry().getType() === 'Point') {
                  if (this.linkAnalysis && this.linkAnalysis.endPoint != null) {
                    removeFeature(this.drawVector, this.linkAnalysis.endPoint)
                  }
                  let endPoint = featureArr[i]
                  this.linkAnalysis.endFlag = false
                  this.$message.success('已选终点')
                  let iconStyle = new Style({
                    image: new Icon({
                      anchor: [0.5, 160],
                      anchorXUnits: 'fraction',
                      anchorYUnits: 'pixels',
                      src: pointEnd,
                      scale: 0.3,
                    }),
                  })
                  let endFeature = new Feature({
                    geometry: new Point(JSON.parse(endPoint.geom)),
                  })
                  endFeature.name = endPoint.name
                  endFeature.geom = endPoint.geom
                  endFeature.setStyle(iconStyle)
                  this.linkAnalysis.endPoint = endFeature
                  this.$parent.setLinkEndPoint(endFeature)
                  addFeature(this.drawVector, endFeature)
                  this.hideMaker()
                }
              }
            }

            if (this.altitudeAnalysis && this.altitudeAnalysis.startFlag) {
              for (let i = 0; i < featureArr.length; i++) {
                if (featureArr[i].getGeometry().getType() === 'Point') {
                  if (this.altitudeAnalysis.startPoint != null) {
                    removeFeature(this.drawVector, this.altitudeAnalysis.startPoint)
                  }
                  let startPoint = featureArr[i]
                  this.altitudeAnalysis.startFlag = false
                  this.$message.success('已选起点')
                  let iconStyle = new Style({
                    image: new Icon({
                      anchor: [0.5, 160],
                      anchorXUnits: 'fraction',
                      anchorYUnits: 'pixels',
                      src: pointStart,
                      scale: 0.3,
                    }),
                  })
                  let startFeature = new Feature({
                    geometry: new Point(JSON.parse(startPoint.geom)),
                  })
                  startFeature.name = startPoint.name
                  startFeature.geom = startPoint.geom
                  startFeature.feature = startPoint.feature
                  startFeature.setStyle(iconStyle)
                  this.altitudeAnalysis.startPoint = startFeature
                  addFeature(this.drawVector, startFeature)
                  this.hideMaker()

                  // 调用回调
                  if (this.altitudeAnalysis.startPointSelectedCallback) {
                    this.altitudeAnalysis.startPointSelectedCallback(this.getAltitudeStartPoint())
                  }
                }
              }
            }
            if (this.altitudeAnalysis && this.altitudeAnalysis.endFlag) {
              for (let i = 0; i < featureArr.length; i++) {
                if (featureArr[i].getGeometry().getType() === 'Point') {
                  if (this.altitudeAnalysis.endPoint != null) {
                    removeFeature(this.drawVector, this.altitudeAnalysis.endPoint)
                  }
                  let endPoint = featureArr[i]
                  this.altitudeAnalysis.endFlag = false
                  this.$message.success('已选终点')
                  let iconStyle = new Style({
                    image: new Icon({
                      anchor: [0.5, 160],
                      anchorXUnits: 'fraction',
                      anchorYUnits: 'pixels',
                      src: pointEnd,
                      scale: 0.3,
                    }),
                  })
                  let endFeature = new Feature({
                    geometry: new Point(JSON.parse(endPoint.geom)),
                  })
                  endFeature.name = endPoint.name
                  endFeature.geom = endPoint.geom
                  endFeature.feature = endPoint.feature
                  endFeature.setStyle(iconStyle)
                  this.altitudeAnalysis.endPoint = endFeature
                  addFeature(this.drawVector, endFeature)
                  this.hideMaker()

                  // 调用回调
                  if (this.altitudeAnalysis.endPointSelectedCallback) {
                    this.altitudeAnalysis.endPointSelectedCallback(this.getAltitudeEndPoint())
                  }
                }
              }
            }
            if (this.modifyFlag) {
              this.hideMaker()
              this.removeHighlightFeature()
            }
          }.bind(this)
        )
        map.on(
          'dblclick',
          function (e) {
            let coodinate = e.coordinate
            let pixel = map.getEventPixel(e.originalEvent)
            let featureArr = []
            map.forEachFeatureAtPixel(pixel, (feature) => {
              if (!feature.isHighlightFeature) {
                featureArr.push(feature)
              }
            })
            let feature = featureArr[0]
            if (!feature.geom) {
              for (let i = 0; i < featureArr.length; i++) {
                if (featureArr[i].geom) {
                  feature = featureArr[i]
                  break
                }
              }
            }
            if (feature && !feature.isDrawedFeature && !this.isDrawing) {
              this.highlightFeature(feature, feature.getGeometry().getType())
              //双击要素并回调
              this.$emit('doubleClickMapFeature', feature)
              if (this.$parent.onDblClick) {
                this.$parent.onDblClick(feature)
              }
            }
            if (this.modifyFlag) {
              this.hideMaker()
              this.removeHighlightFeature()
            }
          }.bind(this)
        )
        if (this.mapdata.length > 0) {
          this.initFeatureData(this.mapdata)
        }
      },
      //初始化要素数据
      initFeatureData(data) {
        if (!this.map) {
          return
        }
        let pointSource = this.pointVector.getSource()
        pointSource.clear()
        let lineSource = this.lineVector.getSource()
        lineSource.clear()
        let polygonSource = this.polygonVector.getSource()
        polygonSource.clear()
        let typeMap = {
          POINT: 'Point',
          LINE: 'LineString',
          LINESTRING: 'LineString',
          POLYGON: 'Polygon',
        }
        let typeVector = {
          POINT: 'pointVector',
          LINE: 'lineVector',
          LINESTRING: 'lineVector',
          POLYGON: 'polygonVector',
        }
        this.idTypeMap = {}
        this.mapdata.forEach((element) => {
          if (!this.idTypeMap[element.id]) {
            this.idTypeMap[element.id] = element.typeKey
            let style
            if (element.typeKey == 'POINT') {
              let imgUrl = this.requireImg(element.icon) || this.requireImg(this.pointImgUrlMap[element.feature.scode])
              if (imgUrl) {
                style = new Style({
                  image: new Icon({
                    anchor: [0.5, 100],
                    anchorXUnits: 'fraction',
                    anchorYUnits: 'pixels',
                    src: imgUrl,
                    scale: 0.123,
                  }),
                  text: new Text({
                    textAlign: 'center',
                    textBaseline: 'middle',
                    font: '16px verdana',
                    text: '',
                    fill: new Fill({
                      color: '#ffffff',
                      width: 3,
                    }),
                    stroke: new Stroke({
                      color: '#000000',
                      width: 3,
                    }),
                    offsetX: parseInt(0, 10),
                    offsetY: parseInt(0, 10),
                    placement: 'point', //point 则自动计算面的中心点然后标注  line 则根据面要素的边进行标注
                    overflow: false, //超出面的部分不显示
                  }),
                })
              }
            } else {
              element.fillColor = this.featureIdColorDict[element.id] || element.fillColor
              style = new Style({
                stroke: new Stroke({
                  color: element.lineColor || element.borderColor || '',
                  width: element.lineWidth || element.borderWidth || 1,
                }),
                fill: new Fill({
                  color: element.fillColor || '',
                }),
                text: new Text({
                  textAlign: 'center',
                  textBaseline: 'middle',
                  font: '16px verdana',
                  text: '',
                  fill: new Fill({
                    color: '#ffffff',
                    width: 3,
                  }),
                  stroke: new Stroke({
                    color: '#000000',
                    width: 3,
                  }),
                  offsetX: parseInt(0, 10),
                  offsetY: parseInt(15, 10),
                  placement: 'point', //point 则自动计算面的中心点然后标注  line 则根据面要素的边进行标注
                  overflow: false, //超出面的部分不显示
                }),
              })
              if (element.typeKey === 'LINE' || element.typeKey === 'LINESTRING') {
                let geom = JSON.parse(element.feature.geom)
                this.graphObj.addEdge(geom[0] + '', geom[1] + '')
              }
            }
            let feature = createFeature(typeMap[element.typeKey], JSON.parse(element.feature.geom), style, element.id)
            for (let key in element) {
              feature[key] = element[key]
            }
            feature.feature = element.feature
            feature.geom = element.feature.geom
            feature.lineWidth = element.lineWidth
            feature.lineColor = element.lineColor
            feature.borderWidth = element.borderWidth
            feature.borderColor = element.borderColor
            feature.fillColor = element.fillColor
            feature.showContent = this.featureShowContentDict[element.id]
            if (this.featureShowNameDict[element.id] && style) {
              style.getText().setText(this.featureShowNameDict[element.id])
            }
            let vector = this[typeVector[element.typeKey]]
            addFeature(vector, feature)
          }
        })
      },
      //根据wfsUrl获取features要素
      getFeaturesByWFSUrl(wfsUrl, layers, layerId, layerName, callback) {
        if (wfsUrl && layers && layerId && layerName && callback) {
          let featureUrl =
            wfsUrl.substring(0, wfsUrl.length - 3) +
            'ows?service=WFS&version=1.0.0&request=GetFeature&typeName=' +
            layers +
            '&outputFormat=application%2Fjson'
          let typeMap = {
            POINT: 'POINT',
            MultiLineString: 'LINE',
            POLYGON: 'POLYGON',
          }
          axios
            .get(featureUrl)
            .then(
              function (respon) {
                let rdfeatures = respon.data.features
                let features = []
                for (let rdi = 0; rdi < rdfeatures.length; rdi++) {
                  let rdfeature = rdfeatures[rdi]
                  let geom = JSON.stringify(rdfeature.geometry.coordinates)
                  if (rdfeature.geometry.type == 'MultiLineString' && geom.substring(0, 3) == '[[[') {
                    geom = geom.substring(1, geom.length - 1)
                  }
                  features.push({
                    borderColor: null,
                    borderWidth: null,
                    feature: {
                      borderColor: 'rgba(208, 2, 27, 0.5)',
                      borderWidth: 2,
                      fillColor: 'rgba(59, 185, 115, 0.5)',
                      geom: geom,
                      id: rdfeature.id,
                      layerId: layerId,
                    },
                    fillColor: null,
                    geom: geom,
                    icon: null,
                    id: rdfeature.id,
                    idName: rdfeature.properties.Name || rdfeature.id,
                    key: rdfeature.id,
                    layerId: layerId,
                    layerName: layerName,
                    lineColor: 'rgba(208, 2, 27, 0.5)',
                    lineWidth: '2.0',
                    name: rdfeature.properties.Name,
                    shape: null,
                    typeKey: typeMap[rdfeature.geometry.type],
                  })
                }
                callback({
                  features: features,
                  layerId: layerId,
                })
              }.bind(this)
            )
            .catch(function (error) {
            })
        } else {
          this.$message.warn('要素服务参数有误，请检查！')
        }
      },
      //重新计算地图的宽高
      resizeMap() {
        this.map.updateSize()
      },
      //获取图片
      requireImg(imgName) {
        try {
          let img = require('../../assets/gis-svg/' + imgName)
          return img
        } catch (error) {
          return undefined
        }
      },
      //改变点样式
      changePointStyle(id, url) {
        let feature = this.getFeatureById(id)
        if (this.requireImg(url)) {
          let iconStyle = new Style({
            image: new Icon({
              anchor: [0.5, 100],
              anchorXUnits: 'fraction',
              anchorYUnits: 'pixels',
              src: this.requireImg(url),
              scale: 0.123,
            }),
          })
          feature.feature.scode = url
          feature.setStyle(iconStyle)
        } else {
          feature.setStyle(undefined)
        }
        removeFeature(this.pointVector, feature)
        let timeout = setTimeout(
          function () {
            addFeature(this.pointVector, feature)
          }.bind(this),
          10
        )
      },
      //改变线样式
      changeLineStyle(id, lineColor, lineWidth) {
        let feature = this.getFeatureById(id)
        let style = new Style({
          stroke: new Stroke({
            color: lineColor,
            width: lineWidth,
          }),
        })
        feature.setStyle(style)
        removeFeature(this.lineVector, feature)
        let timeout = setTimeout(
          function () {
            addFeature(this.lineVector, feature)
          }.bind(this),
          10
        )
      },
      //显示弹窗
      showPop(title, content, coordinate) {
        var titleDiv = document.getElementById('popup-title')
        titleDiv.innerHTML = title
        var contentDiv = document.getElementById('popup-content')
        contentDiv.innerHTML = content
        this.popOverlay.setPosition(coordinate) //显示
        this.isShowPop = true
      },
      //隐藏弹窗
      hidePop() {
        this.isShowPop = false
        this.popOverlay.setPosition(undefined) //隐藏
      },
      //显示单个标记
      showMaker(imgUrl, coordinate, callback) {
        this.markerDiv.innerHTML = `<img style="width: 50px; height: 50px;" src="` + imgUrl + `" />`
        if (callback) {
          this.markerDiv.ondblclick = callback
        }
        this.markerOverlay.setPosition(coordinate) //显示
      },
      //移除单个标记
      hideMaker() {
        this.markerOverlay.setPosition(undefined) //隐藏
      },
      //定位到某个要素
      localToFeature(type, featureId) {
        let typeMap = {
          POINT: 'pointVector',
          Point: 'pointVector',
          LINE: 'lineVector',
          LineString: 'lineVector',
          LINESTRING: 'lineVector',
          POLYGON: 'polygonVector',
          Polygon: 'polygonVector',
          Draw: 'drawVector',
        }
        let layer = isLayerExitByLayerId(this.map, typeMap[type])
        if (layer) {
          let featureSource = layer.getSource()
          if (featureSource != null) {
            //console.log(featureSource)
            let feature = featureSource.getFeatureByUid(featureId)
            if (feature != null) {
              localToFeature(this.map, feature)
              this.highlightFeature(feature, type)
            }
          }
        }
      },
      //根据id定位到要素
      localToFeatureById(featureId) {
        let type = this.idTypeMap[featureId]
        this.localToFeature(type, featureId)
      },
      //使某个要素高亮显示
      highlightFeature(feature, type) {
        this.$parent.selectedFeature = feature
        let hFeature
        if (type === 'LINE' || type === 'LineString') {
          hFeature = new Feature(new LineString(JSON.parse(feature.geom), 'XY'))
        } else if (type === 'POLYGON' || type === 'Polygon') {
          hFeature = new Feature(new Polygon([JSON.parse(feature.geom)]))
        } else {
          hFeature = new Feature(new Point(JSON.parse(feature.geom)))
          this.showMaker(
            localGif,
            JSON.parse(feature.geom),
            function () {
              if (this.$parent.onDblClick) {
                this.$parent.onDblClick(feature)
              }
            }.bind(this)
          )
        }
        this.hFeature = hFeature
        highlightFeature(this.map, hFeature)
      },
      highlightGeoms(geoms) {
        this.hFeature = new Feature(new LineString(geoms, 'XY'))
        localToFeature(this.map, this.hFeature)
        highlightFeature(this.map, this.hFeature)
      },
      //移除高亮显示
      removeHighlightFeature() {
        if (this.hFeature != null) {
          removeHighlightFeature(this.map, this.hFeature)
          this.hFeature = null
        }
      },
      //根据id获取要素
      getFeatureById(id) {
        return (
          this.pointVector.getSource().getFeatureByUid(id) ||
          this.lineVector.getSource().getFeatureByUid(id) ||
          this.polygonVector.getSource().getFeatureByUid(id)
        )
      },
      //获取feature的坐标
      getGeom(feature) {
        if (feature && feature.getGeometry()) {
          let length = feature.getGeometry().flatCoordinates.length
          let pointArr = feature.getGeometry().flatCoordinates
          let coor = []
          for (let index = 0; index < length; index += 2) {
            let flag = true
            coor.find(function (value) {
              if (value[0] === pointArr[index] && value[1] === pointArr[index + 1]) {
                flag = false
              }
            })
            if (flag) {
              coor.push([pointArr[index], pointArr[index + 1]])
            }
          }
          return coor.length === 1 ? JSON.stringify(coor[0]) : JSON.stringify(coor)
        }
        return ''
      },
      //获取样式
      getDrawStyle(drawType) {
        return {
          LineString: new Style({
            stroke: new Stroke({
              color: this.strokeColors.hex,
              width: this.strokeWidth,
            }),
          }),
          Polygon: new Style({
            fill: new Fill({
              color: `rgba(${this.fillColors.rgba.r}, ${this.fillColors.rgba.g}, ${this.fillColors.rgba.b}, ${this.fillColors.rgba.a})`,
            }),
            stroke: new Stroke({
              color: `rgba(${this.strokeColors.rgba.r}, ${this.strokeColors.rgba.g}, ${this.strokeColors.rgba.b}, ${this.strokeColors.rgba.a})`,
              width: this.strokeWidth,
            }),
          }),
        }[drawType]
      },
      drawSinglePoint(callback) {
        this.isDrawing = true
        this.drawedFeatures = []
        this.drawType = 'Point'
        let drawSource = this.drawVector.getSource()
        drawSource.clear()
        this.hideMaker()
        this.draw = new Draw({
          source: drawSource,
          type: this.drawType,
        })
        this.map.addInteraction(this.draw)
        this.draw.on(
          'drawend',
          function (e) {
            e.feature.geom = this.getGeom(e.feature)
            this.map.removeInteraction(this.draw)
            this.drawedFeatures.push(e.feature)
            this.isDrawing = false
            this.draw = undefined
            this.showMaker(localGif, JSON.parse(this.getGeom(e.feature)))
            if (callback) {
              callback(e.feature)
            }
          }.bind(this)
        )
      },
      drawSingleLineString(callback) {
        this.removeHighlightFeature()
        this.isDrawing = true
        this.drawedFeatures = []
        this.drawType = 'LineString'
        let drawSource = this.drawVector.getSource()
        drawSource.clear()
        this.hideMaker()
        this.draw = new Draw({
          source: drawSource,
          type: this.drawType,
        })
        this.map.addInteraction(this.draw)
        this.draw.on(
          'drawend',
          function (e) {
            e.feature.setStyle(this.getDrawStyle(this.drawType))
            e.feature.fillColor = `rgba(${this.fillColors.rgba.r}, ${this.fillColors.rgba.g}, ${this.fillColors.rgba.b}, ${this.fillColors.rgba.a})`
            e.feature.strokeColor = `rgba(${this.strokeColors.rgba.r}, ${this.strokeColors.rgba.g}, ${this.strokeColors.rgba.b}, ${this.strokeColors.rgba.a})`
            e.feature.strokeWidth = this.strokeWidth
            e.feature.geom = this.getGeom(e.feature)
            this.map.removeInteraction(this.draw)
            this.drawedFeatures.push(e.feature)
            this.isDrawing = false
            this.draw = undefined
            if (callback) {
              callback(e.feature)
            }
          }.bind(this)
        )
      },
      drawSinglePolygon(callback) {
        this.removeHighlightFeature()
        this.isDrawing = true
        this.drawedFeatures = []
        this.drawType = 'Polygon'
        let drawSource = this.drawVector.getSource()
        drawSource.clear()
        this.hideMaker()
        this.draw = new Draw({
          source: drawSource,
          type: this.drawType,
        })
        this.map.addInteraction(this.draw)
        this.draw.on(
          'drawend',
          function (e) {
            e.feature.setStyle(this.getDrawStyle(this.drawType))
            e.feature.fillColor = `rgba(${this.fillColors.rgba.r}, ${this.fillColors.rgba.g}, ${this.fillColors.rgba.b}, ${this.fillColors.rgba.a})`
            e.feature.strokeColor = `rgba(${this.strokeColors.rgba.r}, ${this.strokeColors.rgba.g}, ${this.strokeColors.rgba.b}, ${this.strokeColors.rgba.a})`
            e.feature.strokeWidth = this.strokeWidth
            e.feature.geom = this.getGeom(e.feature)
            this.map.removeInteraction(this.draw)
            this.drawedFeatures.push(e.feature)
            this.isDrawing = false
            this.draw = undefined
            if (callback) {
              callback(e.feature)
            }
          }.bind(this)
        )
      },
      startDraw(drawType, style) {
        if (!drawType) {
          return
        }
        this.isDrawing = true
        this.deleteDrawedFeatureFlag = false
        this.drawType = drawType
        if (this.draw) {
          this.map.removeInteraction(this.draw)
        }
        let drawSource = this.drawVector.getSource()
        this.draw = new Draw({
          source: drawSource,
          type: drawType,
        })
        this.map.addInteraction(this.draw)
        this.draw.on('drawstart', function (e) {
        })
        this.draw.on(
          'drawend',
          function (e) {
            e.feature.isDrawedFeature = true
            e.feature.setStyle(this.getDrawStyle(drawType))
            e.feature.fillColor = `rgba(${this.fillColors.rgba.r}, ${this.fillColors.rgba.g}, ${this.fillColors.rgba.b}, ${this.fillColors.rgba.a})`
            e.feature.strokeColor = `rgba(${this.strokeColors.rgba.r}, ${this.strokeColors.rgba.g}, ${this.strokeColors.rgba.b}, ${this.strokeColors.rgba.a})`
            e.feature.strokeWidth = this.strokeWidth
            if (e.feature.getGeometry().getType() === 'LineString' && this.lineStringSlice) {
              let geoms = this.getGeom(e.feature)
              geoms = JSON.parse(geoms)
              if (this.drawedFeatureNodeX != null && this.drawedFeatureNodeY != null) {
                let geom = geoms[geoms.length - 1]
                this.modifyPointMap[geom[0]] = this.drawedFeatureNodeX
                this.modifyPointMap[geom[1]] = this.drawedFeatureNodeY
                this.$message.success('节点已衔接')
              }
              let timestamp = new Date().getTime()
              for (let i = 0; i < geoms.length - 1; i++) {
                timestamp = timestamp + i
                let x1 = this.modifyPointMap[geoms[i][0]] || geoms[i][0]
                let y1 = this.modifyPointMap[geoms[i][1]] || geoms[i][1]
                let x2 = this.modifyPointMap[geoms[i + 1][0]] || geoms[i + 1][0]
                let y2 = this.modifyPointMap[geoms[i + 1][1]] || geoms[i + 1][1]
                let geom = '[[' + x1 + ',' + y1 + '],[' + x2 + ',' + y2 + ']]'
                let tempFeature = new Feature(new LineString(JSON.parse(geom), 'XY'))
                tempFeature.isDrawedFeature = true
                tempFeature.setStyle(this.getDrawStyle(drawType))
                tempFeature.fillColor = `rgba(${this.fillColors.rgba.r}, ${this.fillColors.rgba.g}, ${this.fillColors.rgba.b}, ${this.fillColors.rgba.a})`
                tempFeature.strokeColor = `rgba(${this.strokeColors.rgba.r}, ${this.strokeColors.rgba.g}, ${this.strokeColors.rgba.b}, ${this.strokeColors.rgba.a})`
                tempFeature.strokeWidth = this.strokeWidth
                tempFeature.geom = geom
                tempFeature.ol_uid = timestamp
                tempFeature.isDrawedFeature = true
                this.drawedFeatures.push(tempFeature)
                addFeature(this.drawVector, tempFeature)
                let point1 = new Feature({
                  geometry: new Point([x1, y1]),
                })
                point1.isDrawedFeature = true
                point1.isDrawedFeatureNode = true
                point1.ol_uid = timestamp + 'p1'
                addFeature(this.drawVector, point1)
                let point2 = new Feature({
                  geometry: new Point([x2, y2]),
                })
                point2.isDrawedFeature = true
                point2.isDrawedFeatureNode = true
                point2.ol_uid = timestamp + 'p2'
                addFeature(this.drawVector, point2)
              }
              let timeout = setTimeout(() => {
                this.modifyPointMap = {}
                removeFeature(this.drawVector, e.feature)
                timeout = undefined
              }, 10)
            } else if (e.feature.getGeometry().getType() === 'Point') {
              let pointStyle = new Style({
                image: new Icon({
                  anchor: [0.5, 500],
                  anchorXUnits: 'fraction',
                  anchorYUnits: 'pixels',
                  src: localGif,
                  scale: 0.123,
                }),
              })
              let geom = JSON.parse(this.getGeom(e.feature))
              if (this.drawedFeatureNodeX != null && this.drawedFeatureNodeY != null) {
                geom = [this.drawedFeatureNodeX, this.drawedFeatureNodeY]
              }
              let point = new Feature({
                geometry: new Point(geom),
              })
              point.setStyle(pointStyle)
              point.geom = this.getGeom(point)
              this.drawedFeatures.push(point)
              if (this.fireAnalysis && this.fireAnalysis.flag) {
                this.hideMaker()
                this.isDrawing = false
                this.fireAnalysis.point = point
                this.map.removeInteraction(this.draw)
                this.drawFirePointBuffer()
                // addFeature(this.drawVector, this.fireAnalysis.point)
                let timeout = setTimeout(() => {
                  removeFeature(this.drawVector, e.feature)
                  timeout = undefined
                }, 10)
              }
            } else {
              e.feature.geom = this.getGeom(e.feature)
              this.drawedFeatures.push(e.feature)
            }
          }.bind(this)
        )
      },
      //平移
      panMap() {
        this.removeLineNodes()
        if (this.draw) {
          this.map.removeInteraction(this.draw)
          this.isDrawing = false
          this.deleteDrawedFeatureFlag = false
          // this.linkAnalysis.startFlag = false
          // this.linkAnalysis.endFlag = false
          // this.altitudeAnalysis.startFlag = false
          // this.altitudeAnalysis.endFlag = false
        }
      },
      //捕捉
      deleteDrawedFeature() {
        this.map.removeInteraction(this.draw)
        this.isDrawing = false
        this.deleteDrawedFeatureFlag = !this.deleteDrawedFeatureFlag
        // this.linkAnalysis.startFlag = false
        // this.linkAnalysis.endFlag = false
        // this.altitudeAnalysis.startFlag = false
        // this.altitudeAnalysis.endFlag = false
      },
      //绘点
      drawMapPoint() {
        this.drawLineNodes()
        this.startDraw('Point')
      },
      //绘线
      drawMapLineString() {
        this.drawLineNodes()
        this.startDraw('LineString')
      },
      //绘面
      drawMapPolygon() {
        this.removeLineNodes()
        this.startDraw('Polygon')
      },
      //移除所有线段两端的参考点
      removeLineNodes() {
        if (this.lineNodeArr.length === 0) {
          return
        }
        this.lineNodeArr.forEach((element) => {
          removeFeature(this.drawVector, element)
        })
        this.lineNodeArr = []
      },
      //描绘所有线段两端的参考点
      drawLineNodes() {
        this.removeLineNodes()
        this.mapdata.forEach((element) => {
          if (element.typeKey === 'LINE' || element.typeKey === 'LINESTRING') {
            let geom = JSON.parse(element.feature.geom)
            let point1 = new Feature({
              geometry: new Point(geom[0]),
            })
            point1.isDrawedFeature = true
            point1.isDrawedFeatureNode = true
            this.lineNodeArr.push(point1)
            addFeature(this.drawVector, point1)
            let point2 = new Feature({
              geometry: new Point(geom[1]),
            })
            point2.isDrawedFeature = true
            point2.isDrawedFeatureNode = true
            this.lineNodeArr.push(point2)
            addFeature(this.drawVector, point2)
          }
        })
      },
      //获取当前描绘的要素
      getDrawedFeatures() {
        return this.drawedFeatures
      },
      //编辑当前要素
      modifyFeature() {
        this.hideMaker()
        this.removeHighlightFeature()
        this.modifyFlag = true
        this.ModifyObj.setActive(true) //激活几何图形修改控件
      },
      //停止编辑要素
      stopModifyFeature() {
        this.modifyFlag = false
        this.ModifyObj.setActive(false) //激活几何图形修改控件
      },
      //保存当前描绘
      drawSave() {
        if (this.$parent.saveFeature) {
          this.$parent.saveFeature(this.drawedFeatures)
        }
      },
      //清空当前描绘
      drawCancel() {
        this.hideMaker()
        this.removeLineNodes()
        this.stopModifyFeature()
        this.modifyPointMap = {}
        this.deleteDrawedFeatureFlag = false
        this.valveClosingPlan.flag = false
        this.linkAnalysis.startFlag = false
        this.linkAnalysis.endFlag = false
        this.altitudeAnalysis.startFlag = false
        this.altitudeAnalysis.endFlag = false
        this.drawedFeatures = []
        this.drawVector.getSource().clear()
        if (this.draw) {
          this.map.removeInteraction(this.draw)
          this.draw = undefined
          this.isDrawing = false
        }
        this.removeHighlightFeature()
        removeAllHighlightFeature(this.map)
      },

      //图层控制开始
      onExpand(expandedKeys) {
        this.expandedKeys = expandedKeys
        this.autoExpandParent = false
      },
      onCheck(checkedKeys) {
        this.checkedKeys = checkedKeys
        let rtKeys = []
        checkedKeys.forEach((element) => {
          if (element != '0-0-0') {
            rtKeys.push(element)
          }
        })
        removeAllHighlightFeature(this.map)
        this.$emit('layerControl', rtKeys)
        // if (this.$parent.layerControl) {
        //   this.$parent.layerControl(rtKeys)
        // }
      },
      onSelect(selectedKeys, info) {
        // this.selectedKeys = selectedKeys;
      },
      //图层控制结束
      //地图定位开始
      onChangeLocalTabs(key) {
        this.drawCancel()
      },
      //根据X，Y坐标定位
      localToXY(x, y) {
        this.coordinateXY.locationX = x
        this.coordinateXY.locationY = y
        if (x === '' || y === '') {
          return
        }
        this.hideMaker()
        this.showMaker(localGif, [x, y])
        localToXY(this.map, parseFloat(x) + 0.00015, parseFloat(y))
        // localToXY(this.map, x, y)
      },
      //重置X，Y坐标定位
      resetXY() {
        this.hideMaker()
        this.coordinateXY.locationX = ''
        this.coordinateXY.locationY = ''
      },
      //交叉路口定位到交叉点
      localToRoadXY(lineGeom1, lineGeom2) {
        let line1 = turf.lineString(lineGeom1)
        let line2 = turf.lineString(lineGeom2)
        let intersection = turf.lineIntersect(line1, line2)
        if (intersection.features.length === 0) {
          this.$message.warn('没有交叉路口')
          return
        }
        intersection.features.forEach((turfFeature) => {
          let feature = new GeoJSON().readFeature(turfFeature)
          feature.geom = this.getGeom(feature)
          localToFeature(this.map, feature)
          this.highlightFeature(feature, feature.getGeometry().getType())
        })
      },
      onSearch(value) {
      },

      //表格点击行触发方法
      localRowClick(record, index) {
        return {
          on: {
            click: () => {
            },
          },
        }
      },
      //地图定位结束

      //查询统计开始
      getPolygonVectorFeatures() {
        return this.polygonVector.getSource().getFeatures()
      },
      getLineVectorFeatures() {
        return this.lineVector.getSource().getFeatures()
      },
      buffer(bufferArr, polygon) {
        return buffer(bufferArr, polygon)
      },
      //切换tabs
      onChangeAnalysisTabs(key) {
        this.drawCancel()
        if (key === '3') {
          let polygonArr = this.polygonVector.getSource().getFeatures()
          let treeData = this.listData2TreeData(polygonArr)
          this.pipeLineLength.tree.dataList = polygonArr
          this.pipeLineLength.tree.gData = treeData
          let pipe_material = this.$parent.getDictItem('pipe_material')
          pipe_material.forEach((element) => {
            element.label = element.title
            this.pipeLineLength.pipeMaterial.map[element.value] = element.title
          })
          let pipe_diameter = this.$parent.getDictItem('pipe_diameter')
          pipe_diameter.forEach((element) => {
            element.label = element.title
          })
          this.pipeLineLength.pipeMaterial.plainOptions = pipe_material
          this.pipeLineLength.pipeDiameter.plainOptions = pipe_diameter
        }
        if (key === '4') {
          let polygonArr = this.polygonVector.getSource().getFeatures()
          let treeData = this.listData2TreeData(polygonArr)
          this.devicesCount.tree.dataList = polygonArr
          this.devicesCount.tree.gData = treeData
          let device_type = this.$parent.getDictItem('device_type')
          device_type.forEach((element) => {
            element.label = element.title
            this.devicesCount.devicesType.map[element.value] = element.title
          })
          this.devicesCount.devicesType.plainOptions = device_type
        }
      },
      //道路缓冲查询下拉图层
      onStatisticsLayerChange(e) {
        this.drawCancel()
        this.removeHighlightFeature()
        removeAllHighlightFeature(this.map)
        this.roadBuffer.roadData = []
        this.roadBuffer.roadId = ''
        this.roadBuffer.roadOpt = null
      },
      onStatisticsRoadSearch(value) {
        if (value != '') {
          let roadData = this.$parent.getFeatureDataByLayerIdName(this.roadBuffer.layerId, value)
          this.roadBuffer.roadData = roadData
        }
      },
      //道路缓冲查询下拉道路
      onStatisticsRoadChange(key, com, distance) {
        this.roadBuffer.distance = distance
        this.drawCancel()
        this.removeHighlightFeature()
        removeAllHighlightFeature(this.map)
        this.roadBuffer.roadOpt = com.data.attrs.optVal
        this.drawBuffer()
      },
      onStatisticsDistanceChange(distance) {
        this.roadBuffer.distance = distance
        this.drawCancel()
        this.removeHighlightFeature()
        removeAllHighlightFeature(this.map)
        this.drawBuffer()
      },
      //道路缓冲查询按钮
      roadBufferSearch(distance, type) {
        this.hideMaker()
        this.roadBuffer.distance = distance
        this.roadBuffer.type = type
        let bufferArr = []
        if (this.roadBuffer.type === 'POINT') {
          bufferArr = this.pointVector.getSource().getFeatures()
        } else if (this.roadBuffer.type === 'LINE') {
          let lineArr = this.lineVector.getSource().getFeatures()
          lineArr.forEach((element) => {
            let geom = JSON.parse(element.geom)
            if (geom.length === 2) {
              bufferArr.push(element)
            }
          })
          this.drawBuffer()
        }
        if (bufferArr.length > 0) {
          let bufferRes = buffer(bufferArr, this.roadBuffer.fbuffered)
          this.roadBuffer.bufferedRes = bufferRes
          highlightFeatures(this.map, bufferRes, defaultIcon)
          let layerIdMap = {}
          bufferRes.forEach((element) => {
            if (layerIdMap[element.layerId]) {
              layerIdMap[element.layerId].push(element.feature.id)
            } else {
              layerIdMap[element.layerId] = []
              layerIdMap[element.layerId].push(element.feature.id)
            }
          })
          let paramArr = []
          for (let key in layerIdMap) {
            let idsStr = layerIdMap[key].join(',')
            paramArr.push({
              layer: key,
              type: this.roadBuffer.type,
              ids: idsStr,
            })
          }
          let localMap = {
            POINT: 'Point',
            LINE: 'LineString',
          }
          this.roadBuffer.table.localType = localMap[this.roadBuffer.type]
          return paramArr
          // this.$parent.getPointsOrLinesDetail(paramArr[0], (res) => {
          //   let localMap = {
          //     POINT: 'Point',
          //     LINE: 'LineString',
          //   }
          //   this.roadBuffer.table.tableData = res
          //   this.roadBuffer.table.localType = localMap[this.roadBuffer.type]
          // })
        }
      },
      drawBuffer() {
        let distance = Number(this.roadBuffer.distance)
        let geom = this.roadBuffer.roadOpt.feature.geom
        let gsonline = turf.lineString(JSON.parse(geom))
        let buffered = turf.buffer(gsonline, distance, {
          units: 'meters',
        })
        // 原始圆头buffer
        this.roadBuffer.fbuffered = new GeoJSON().readFeature(buffered)
        this.roadBuffer.fbuffered.isHighlightFeature = true
        let drawSource = this.drawVector.getSource()
        drawSource.addFeature(this.roadBuffer.fbuffered)
        localToFeature(this.map, this.roadBuffer.fbuffered)
      },
      //道路缓冲查询导出
      roadBufferExport(columns, tableData, title) {
        ExportExcel(columns, tableData, title)
      },
      //道路缓冲查询表格定位
      roadBufferRowClick(record, index) {
        if (this.roadBuffer.type === 'POINT') {
          let featureSource = isLayerExitByLayerId(this.map, 'pointVector').getSource()
          let feature = featureSource.getFeatureByUid(record.id)
          if (feature != null) {
            removeAllHighlightFeature(this.map)
            let hArr = []
            for (let i = 0; i < this.roadBuffer.bufferedRes.length; i++) {
              if (this.roadBuffer.bufferedRes[i].id != record.id) {
                hArr.push(this.roadBuffer.bufferedRes[i])
              }
            }
            highlightFeatures(this.map, hArr, defaultIcon)
            this.showMaker(localGif, JSON.parse(feature.geom))
          }
        } else {
          this.localToFeature(this.roadBuffer.type, record.id)
        }
      },

      //管线要素查询按钮
      pipeLineSearchSearch() {
        let param = {
          layers: this.disabledKey,
          type: this.pipeLineSearch.type,
          field: this.pipeLineSearch.field,
          operator: this.pipeLineSearch.operator,
          value: this.pipeLineSearch.value,
        }
        this.$parent.findPointsOrLines(param, (res) => {
          let localMap = {
            POINT: 'Point',
            LINE: 'LineString',
          }
          this.pipeLineSearch.table.tableData = res
          this.pipeLineSearch.table.localType = localMap[this.pipeLineSearch.type]
        })
      },
      //管线要素查询导出
      pipeLineSearchExport(columns, tableData, title) {
        ExportExcel(columns, tableData, title)
      },
      //管线要素查询表格定位
      pipeLineSearchRowClick(record, index, localType) {
        this.localToFeature(localType, record.id)
      },
      //查询统计结束

      //管线长度查询开始
      onPipeLineLengthTreeExpand(expandedKeys) {
        this.pipeLineLength.tree.expandedKeys = expandedKeys
        this.pipeLineLength.tree.autoExpandParent = false
      },
      onPipeLineLengthTreeChange(e) {
        let value = e.target.value
        let expandedKeys = this.pipeLineLength.tree.dataList
          .map((item) => {
            if (item.title.indexOf(value) > -1) {
              return getParentKey(item.key, this.pipeLineLength.tree.gData)
            }
            return null
          })
          .filter((item, i, self) => item && self.indexOf(item) === i)
        Object.assign(this.pipeLineLength.tree, {
          expandedKeys,
          searchValue: value,
          autoExpandParent: true,
        })
      },
      onPipeLineLengthTreeSelect(selectedKeys, info) {
        let polygonId = selectedKeys[0]
        this.pipeLineLength.tree.selectedKey = polygonId
        this.localToFeature('Polygon', polygonId)
      },
      //材质选择
      onChangePipeMaterial(checkedList) {
        this.pipeLineLength.pipeMaterial.indeterminate =
          !!checkedList.length &&
          this.pipeLineLength.pipeMaterial.checkedList.length < this.pipeLineLength.pipeMaterial.plainOptions.length
        this.pipeLineLength.pipeMaterial.checkAll =
          checkedList.length === this.pipeLineLength.pipeMaterial.plainOptions.length
      },
      //材质全选
      onCheckAllChangePipeMaterial(e) {
        let checkedList = []
        if (e.target.checked) {
          this.pipeLineLength.pipeMaterial.plainOptions.forEach((element) => {
            checkedList.push(element.value)
          })
        }
        Object.assign(this.pipeLineLength.pipeMaterial, {
          checkedList: checkedList,
          indeterminate: false,
          checkAll: e.target.checked,
        })
      },
      //口径选择
      onChangePipeDiameter(checkedList) {
        this.pipeLineLength.pipeDiameter.indeterminate =
          !!checkedList.length && checkedList.length < this.pipeLineLength.pipeDiameter.plainOptions.length
        this.pipeLineLength.pipeDiameter.checkAll =
          checkedList.length === this.pipeLineLength.pipeDiameter.plainOptions.length
      },
      //口径全选
      onCheckAllChangePipeDiameter(e) {
        let checkedList = []
        if (e.target.checked) {
          this.pipeLineLength.pipeDiameter.plainOptions.forEach((element) => {
            checkedList.push(element.value)
          })
        }
        Object.assign(this.pipeLineLength.pipeDiameter, {
          checkedList: checkedList,
          indeterminate: false,
          checkAll: e.target.checked,
        })
      },
      //点击搜索
      pipeLineLengthSearch() {
        this.pipeLineLength.table.totalLength = 0
        this.pipeLineLength.table.tableData = []
        let bufferIds = []
        let isBuffered = false
        if (this.pipeLineLength.tree.selectedKey != '000' && this.pipeLineLength.tree.selectedKey != '') {
          isBuffered = true
          let polygon = this.getFeatureById(this.pipeLineLength.tree.selectedKey)
          let bufferArr = []
          let lineArr = this.lineVector.getSource().getFeatures()
          lineArr.forEach((element) => {
            let geom = JSON.parse(element.geom)
            if (geom.length === 2) {
              bufferArr.push(element)
            }
          })
          let bufferRes = buffer(bufferArr, polygon)
          bufferRes.forEach((element) => {
            bufferIds.push(element.id)
          })
        }
        if (bufferIds.length === 0 && isBuffered) {
          return
        }
        if (this.pipeLineLength.pipeMaterial.checkedList.length === 0) {
          this.$message.warn('至少勾选一项材质!')
          return
        }
        if (this.pipeLineLength.pipeDiameter.checkedList.length === 0) {
          this.$message.warn('至少勾选一项口径!')
          return
        }
        let param = {
          lineIds: bufferIds.join(','),
          material: this.pipeLineLength.pipeMaterial.checkedList.join(','),
          dn: this.pipeLineLength.pipeDiameter.checkedList.join(','),
        }
        this.$parent.getPipelineLength(
          param,
          function (res) {
            if (res === null) {
              return
            }
            res.forEach((element) => {
              element.material = this.pipeLineLength.pipeMaterial.map[element.material]
              this.pipeLineLength.table.totalLength += Number(element.length)
            })
            this.pipeLineLength.table.tableData = res
          }.bind(this)
        )
      },
      //导出
      pipeLineLengthExport(columns, tableData, title) {
        ExportExcel(columns, tableData, title)
      },
      //管线长度查询结束

      //设施数量查询开始
      onDevicesCountTreeExpand(expandedKeys) {
        this.devicesCount.tree.expandedKeys = expandedKeys
        this.devicesCount.tree.autoExpandParent = false
      },
      onDevicesCountTreeChange(e) {
        let value = e.target.value
        let expandedKeys = this.devicesCount.tree.dataList
          .map((item) => {
            if (item.title.indexOf(value) > -1) {
              return getParentKey(item.key, this.devicesCount.tree.gData)
            }
            return null
          })
          .filter((item, i, self) => item && self.indexOf(item) === i)
        Object.assign(this.devicesCount.tree, {
          expandedKeys,
          searchValue: value,
          autoExpandParent: true,
        })
      },
      onDevicesCountTreeSelect(selectedKeys, info) {
        let polygonId = selectedKeys[0]
        this.devicesCount.tree.selectedKey = polygonId
        this.localToFeature('Polygon', polygonId)
      },
      //设备类型选择
      onChangeDevicesCount(checkedList) {
        this.devicesCount.devicesType.indeterminate =
          !!checkedList.length && checkedList.length < this.devicesCount.devicesType.plainOptions.length
        this.devicesCount.devicesType.checkAll = checkedList.length === this.devicesCount.devicesType.plainOptions.length
      },
      //设备类型全选
      onCheckAllChangeDevicesCount(e) {
        let checkedList = []
        if (e.target.checked) {
          this.devicesCount.devicesType.plainOptions.forEach((element) => {
            checkedList.push(element.value)
          })
        }
        Object.assign(this.devicesCount.devicesType, {
          checkedList: checkedList,
          indeterminate: false,
          checkAll: e.target.checked,
        })
      },
      //查询
      devicesCountSearch() {
        this.devicesCount.table.totalNum = 0
        this.devicesCount.table.tableData = []
        let bufferIds = []
        let isBuffered = false
        if (this.devicesCount.tree.selectedKey != '000' && this.devicesCount.tree.selectedKey != '') {
          isBuffered = true
          let polygon = this.getFeatureById(this.devicesCount.tree.selectedKey)
          let bufferArr = []
          let pointArr = this.pointVector.getSource().getFeatures()
          pointArr.forEach((element) => {
            let geom = JSON.parse(element.geom)
            if (geom.length === 2) {
              bufferArr.push(element)
            }
          })
          let bufferRes = buffer(bufferArr, polygon)
          bufferRes.forEach((element) => {
            bufferIds.push(element.id)
          })
        }
        if (bufferIds.length === 0 && isBuffered) {
          return
        }
        if (this.devicesCount.devicesType.checkedList.length === 0) {
          this.$message.warn('至少勾选一项设施类型!')
          return
        }
        let param = {
          lineIds: bufferIds.join(','),
          scode: this.devicesCount.devicesType.checkedList.join(','),
        }
        this.$parent.getPointFeatureCount(
          param,
          function (res) {
            if (res === null) {
              return
            }
            res.forEach((element) => {
              element.scode = this.devicesCount.devicesType.map[element.scode]
              this.devicesCount.table.totalNum += Number(element.count)
            })
            this.devicesCount.table.tableData = res
          }.bind(this)
        )
      },
      //导出
      devicesCountExport(columns, tableData, title) {
        ExportExcel(columns, tableData, title)
      },
      //设施数量查询结束

      //空间分析开始
      //切换tabs
      onChangeSpatialAnalysisTabs() {
        this.drawCancel()
      },
      //关阀预案开始
      //点选
      selectValveClosingPlanStart() {
        this.valveClosingPlan.flag = true
      },
      //清除
      cleanSelectValveClosingPlanStart() {
        this.valveClosingPlan.flag = false
        this.valveClosingPlan.selectFeature = null
        this.cleanValveClosingPlanAnalysisResult()
        this.drawCancel()
      },
      //爆管分析结果清除
      cleanValveClosingPlanAnalysisResult() {
        (this.valveClosingPlan.valveClosingPlanResultMap = {}),
          (this.valveClosingPlan.plainOptions = []),
          (this.valveClosingPlan.checkedList = []),
          (this.valveClosingPlan.indeterminate = false),
          (this.valveClosingPlan.checkAll = false),
          (this.valveClosingPlan.table.tableData = [])
        removeAllHighlightFeature(this.map)
        this.hideMaker()
      },
      //爆管分析
      valveClosingPlanAnalysis() {
        if (this.valveClosingPlan.selectFeature == null) {
          this.$message.warn('爆管位置未选择！')
          return
        }
        this.cleanValveClosingPlanAnalysisResult()
        let startFeature = this.valveClosingPlan.selectFeature
        let pointArr = this.pointVector.getSource().getFeatures()
        let fmPointArr = []
        pointArr.forEach((element) => {
          if (
            element.feature.scode == ('5' || 5) &&
            element.feature.valveBroken != ('1' || 1) &&
            element.feature.geom != startFeature.geom
          ) {
            fmPointArr.push(element)
          }
        })
        let startPointStr
        if (startFeature.getGeometry().getType() == 'Point') {
          startPointStr = JSON.parse(startFeature.geom)[0] + ',' + JSON.parse(startFeature.geom)[1]
        }
        let linePointStr1, linePointStr2
        if (startFeature.getGeometry().getType() == 'LineString') {
          linePointStr1 = JSON.parse(startFeature.geom)[0][0] + ',' + JSON.parse(startFeature.geom)[0][1]
          linePointStr2 = JSON.parse(startFeature.geom)[1][0] + ',' + JSON.parse(startFeature.geom)[1][1]
          startPointStr = this.valveClosingPlan.markedFeature.geom[0] + ',' + this.valveClosingPlan.markedFeature.geom[1]
          this.graphObj.addEdge(this.valveClosingPlan.markedFeature.geom + '', linePointStr1 + '')
          this.graphObj.addEdge(this.valveClosingPlan.markedFeature.geom + '', linePointStr2 + '')
          this.graphObj.removeEdge(linePointStr1 + '', linePointStr2 + '')
        }
        this.graphObj.bfs(startPointStr)
        let linkLineArr = []
        let endPointStr
        for (let i = 0; i < fmPointArr.length; i++) {
          endPointStr = JSON.parse(fmPointArr[i].geom)[0] + ',' + JSON.parse(fmPointArr[i].geom)[1]
          let paths = this.graphObj.pathTo(startPointStr, endPointStr)

          let str = ''
          if (paths) {
            let linkLine = '['
            while (paths.length > 0) {
              if (paths.length > 1) {
                let tempPath = paths.pop()
                linkLine += '[' + tempPath + '],'
              } else {
                let tempPath = paths.pop()
                linkLine += '[' + tempPath + ']'
              }
            }
            linkLine += ']'
            linkLineArr.push(JSON.parse(linkLine))
          }
        }
        let gradingMap = this.gradingValveClosingPlan(linkLineArr, fmPointArr)
        this.valveClosingPlan.valveClosingPlanResultMap = gradingMap
        let plainOptions = []
        for (let key in gradingMap) {
          plainOptions.push({
            label: key + '级关阀方案',
            value: key,
          })
        }
        this.valveClosingPlan.plainOptions = plainOptions
        if (startFeature.getGeometry().getType() == 'LineString') {
          this.graphObj.addEdge(this.valveClosingPlan.markedFeature.geom + '', linePointStr1 + '')
          this.graphObj.addEdge(this.valveClosingPlan.markedFeature.geom + '', linePointStr2 + '')
          this.graphObj.removeEdge(linePointStr1 + '', linePointStr2 + '')
        }
        return this.valveClosingPlan
      },
      //阀门关闭方案分级
      gradingValveClosingPlan(linkLineArr, fmPointArr) {
        let map = {}
        for (let i = 0; i < linkLineArr.length; i++) {
          let count = 1
          B: for (let j = 0; j < linkLineArr[i].length; j++) {
            for (let k = 0; k < fmPointArr.length; k++) {
              if (linkLineArr[i][j].toString() == JSON.parse(fmPointArr[k].geom).toString()) {
                if (!map[count]) {
                  map[count] = {}
                }
                fmPointArr[k].level = count
                map[count][fmPointArr[k].feature.id] = fmPointArr[k]
                count = count + 1
                continue B
              }
            }
          }
        }
        let gradingMap = {}
        for (let key in map) {
          gradingMap[key] = []
          for (let cKey in map[key]) {
            gradingMap[key].push(map[key][cKey])
          }
        }
        return gradingMap
      },

      //阀门关闭方案选择
      onChangeValveClosingPlan(checkedList) {
        this.valveClosingPlan.indeterminate =
          !!checkedList.length && this.valveClosingPlan.checkedList.length < this.valveClosingPlan.plainOptions.length
        this.valveClosingPlan.checkAll = checkedList.length === this.valveClosingPlan.plainOptions.length
        let resultMap = this.valveClosingPlan.valveClosingPlanResultMap
        let tableData = []
        checkedList.forEach((element) => {
          tableData = tableData.concat(resultMap[element])
        })
        this.valveClosingPlan.table.tableData = tableData
        this.hideMaker()
        highlightFeatures(this.map, tableData, defaultIcon)
        if (tableData.length == 0) {
          removeAllHighlightFeature(this.map)
        }
      },
      //阀门关闭方案全选
      onCheckAllChangeValveClosingPlan(e) {
        let checkedList = []
        if (e.target.checked) {
          this.valveClosingPlan.plainOptions.forEach((element) => {
            checkedList.push(element.value)
          })
        }
        let resultMap = this.valveClosingPlan.valveClosingPlanResultMap
        let tableData = []
        checkedList.forEach((element) => {
          tableData = tableData.concat(resultMap[element])
        })
        this.valveClosingPlan.table.tableData = tableData
        this.hideMaker()
        highlightFeatures(this.map, tableData, defaultIcon)
        if (tableData.length == 0) {
          removeAllHighlightFeature(this.map)
        }
        Object.assign(this.valveClosingPlan, {
          checkedList: checkedList,
          indeterminate: false,
          checkAll: e.target.checked,
        })
      },

      //表格点击行触发方法
      valveClosingPlanRowClick(record, index) {
        let featureSource = isLayerExitByLayerId(this.map, 'pointVector').getSource()
        let feature = featureSource.getFeatureByUid(record.ol_uid)
        if (feature != null) {
          removeAllHighlightFeature(this.map)
          let hArr = []
          for (let i = 0; i < this.valveClosingPlan.table.tableData.length; i++) {
            if (this.valveClosingPlan.table.tableData[i].ol_uid != record.ol_uid) {
              hArr.push(this.valveClosingPlan.table.tableData[i])
            }
          }
          highlightFeatures(this.map, hArr, defaultIcon)
          this.showMaker(localGif, JSON.parse(feature.geom))
        }
      },
      //导出
      valveClosingPlanExport(columns, tableData, title) {
        ExportExcel(columns, tableData, title)
      },
      //关阀预案结束

      //火灾分析开始
      selectFirePoint() {
        if (this.fireAnalysis.point != null) {
          removeFeature(this.drawVector, this.fireAnalysis.point)
        }
        if (this.fireAnalysis.fbuffered != null) {
          removeFeature(this.drawVector, this.fireAnalysis.fbuffered)
        }
        this.fireAnalysis.flag = true
        this.startDraw('Point')
      },
      drawFirePointBuffer(distance) {
        if (this.fireAnalysis.point == null) {
          return
        }
        if (distance) {
          this.fireAnalysis.distance = distance
        }
        if (this.fireAnalysis.fbuffered != null) {
          removeFeature(this.drawVector, this.fireAnalysis.fbuffered)
        }
        distance = Number(this.fireAnalysis.distance)
        let geom = this.fireAnalysis.point.geom
        let gsonline = turf.point(JSON.parse(geom))
        let buffered = turf.buffer(gsonline, distance, {
          units: 'meters',
        })
        // 原始圆头buffer
        this.fireAnalysis.fbuffered = new GeoJSON().readFeature(buffered)
        this.fireAnalysis.fbuffered.isHighlightFeature = true
        let drawSource = this.drawVector.getSource()
        drawSource.addFeature(this.fireAnalysis.fbuffered)
        // this.showMaker(firePng, geom)
        let pointStyle = new Style({
          image: new Icon({
            anchor: [0.5, 200],
            anchorXUnits: 'fraction',
            anchorYUnits: 'pixels',
            src: firePng,
            scale: 0.2,
          }),
        })
        this.fireAnalysis.point.setStyle(pointStyle)
        if (this.fireAnalysis.point != null) {
          removeFeature(this.drawVector, this.fireAnalysis.point)
        }
        drawSource.addFeature(this.fireAnalysis.point)
      },
      fireHydrantSearch() {
        if (this.fireAnalysis.fbuffered == null) {
          this.$message.info('请选择火灾点！')
          return
        }
        this.hideMaker()
        let pointArr = this.pointVector.getSource().getFeatures()
        let bufferArr = []
        pointArr.forEach((element) => {
          if (element.feature.scode != null && element.feature.scode == ('4' || 4)) bufferArr.push(element)
        })
        if (bufferArr.length > 0) {
          removeAllHighlightFeature(this.map)
          let bufferRes = buffer(bufferArr, this.fireAnalysis.fbuffered)
          this.fireAnalysis.bufferedRes = bufferRes
          highlightFeatures(this.map, bufferRes, defaultIcon)
          this.fireAnalysis.table.tableData = bufferRes
        } else {
          this.$message.info('该火灾点附近无消防栓')
        }
        return this.fireAnalysis
      },
      fireAnalysisRowClick(record, index) {
        let featureSource = isLayerExitByLayerId(this.map, 'pointVector').getSource()
        let feature = featureSource.getFeatureByUid(record.ol_uid)
        if (feature != null) {
          removeAllHighlightFeature(this.map)
          let hArr = []
          for (let i = 0; i < this.fireAnalysis.bufferedRes.length; i++) {
            if (this.fireAnalysis.bufferedRes[i].ol_uid != record.ol_uid) {
              hArr.push(this.fireAnalysis.bufferedRes[i])
            }
          }
          highlightFeatures(this.map, hArr, defaultIcon)
          this.showMaker(localGif, JSON.parse(feature.geom))
        }
      },
      fireAnalysisExport(columns, tableData, title) {
        ExportExcel(columns, tableData, title)
      },
      //火灾分析结束

      //连通性分析开始
      selectLinkStartPoint() {
        this.linkAnalysis.startFlag = true
        this.linkAnalysis.endFlag = false
      },
      selectLinkEndPoint() {
        this.linkAnalysis.startFlag = false
        this.linkAnalysis.endFlag = true
      },
      linkedAnalysis(callback) {
        let linkedFlag = false
        let startPoint = this.linkAnalysis.startPoint
        let endPoint = this.linkAnalysis.endPoint

        let startPointStr = JSON.parse(startPoint.geom)[0] + ',' + JSON.parse(startPoint.geom)[1]
        let endPointStr = JSON.parse(endPoint.geom)[0] + ',' + JSON.parse(endPoint.geom)[1]

        this.graphObj.bfs(startPointStr)
        let paths = this.graphObj.pathTo(startPointStr, endPointStr)
        let allPaths = this.graphObj.allPathTo(startPointStr, endPointStr)
        let str = ''
        if (paths) {
          let linkLine = '['
          while (paths.length > 0) {
            if (paths.length > 1) {
              let tempPath = paths.pop()
              str += tempPath + '->'
              linkLine += '[' + tempPath + '],'
            } else {
              let tempPath = paths.pop()
              str += tempPath
              linkLine += '[' + tempPath + ']'
            }
          }
          linkLine += ']'

          let linkFeature = new Feature(new LineString(JSON.parse(linkLine), 'XY'))
          this.hFeature = linkFeature
          highlightFeature(this.map, linkFeature)
          linkedFlag = true
        }
        if (callback) {
          callback(linkedFlag)
        }
      },
      analysising(startPoint, startLineArr, lineArr, endLineArr) {
        let startGeom = JSON.parse(startPoint.geom)
        let lineTree = []
        startLineArr.forEach((element) => {
          let index = lineArr.indexOf(element)
          lineArr.splice(index, 1)
          let lineMap = {}
          lineMap.id = element.id
          lineMap.startGeom = startGeom
          let geom = JSON.parse(element.geom)
          if (startGeom === geom[0] || startGeom === geom[1]) {
            lineMap.endGeom = startGeom === geom[0] ? geom[1] : geom[0]
          }
          lineMap.children = []
          lineTree.push(lineMap)
        })
      },
      //连通性分析结束
      //预警分析开始
      //预警分析
      earlyWarningAnalysising() {
        let param = {
          layer: this.disabledKey + '',
          type: this.earlyWarningAnalysis.type + '',
          period: this.earlyWarningAnalysis.value + '',
        }
        this.$parent.getPointsOrLinesWarningPeriod(param, (res) => {
          this.earlyWarningAnalysis.table.tableData = res
        })
      },
      //导出
      earlyWarningAnalysisingExport(columns, tableData, title) {
        ExportExcel(columns, tableData, title)
      },
      //预警分析结束
      //高程差分析开始
      selectAltitudeStartPoint(callback) {
        this.altitudeAnalysis.startFlag = true
        this.altitudeAnalysis.endFlag = false
        this.altitudeAnalysis.startPointSelectedCallback = callback
      },
      selectAltitudeEndPoint(callback) {
        this.altitudeAnalysis.startFlag = false
        this.altitudeAnalysis.endFlag = true
        this.altitudeAnalysis.endPointSelectedCallback = callback
      },
      getAltitudeStartPoint() {
        return this.altitudeAnalysis.startPoint
      },
      getAltitudeEndPoint() {
        return this.altitudeAnalysis.endPoint
      },
      altitudeAnalysising() {
        if (this.altitudeAnalysis.startPoint == null) {
          this.$message.warn('请选择起点')
          return
        }
        if (this.altitudeAnalysis.endPoint == null) {
          this.$message.warn('请选择终点')
          return
        }
        let startPoint = {
          name: this.altitudeAnalysis.startPoint.name,
          h: this.altitudeAnalysis.startPoint.feature.h,
          address: this.altitudeAnalysis.startPoint.feature.address,
        }
        let endPoint = {
          name: this.altitudeAnalysis.endPoint.name,
          h: this.altitudeAnalysis.endPoint.feature.h,
          address: this.altitudeAnalysis.endPoint.feature.address,
        }
        this.altitudeAnalysis.sPoint = startPoint
        this.altitudeAnalysis.ePoint = endPoint
        let x1 = 100
        let ty1 = 30
        let tx2 = 30
        let ty3 = 180
        if (Number(endPoint.h) > Number(startPoint.h)) {
          x1 = x1 + 400
          ty1 = ty1 + 150
          tx2 = tx2 + 480
          ty3 = ty3 - 150
        }

        let canvas = this.$refs.altitudeCanvas
        let ctx = canvas.getContext('2d')
        ctx.clearRect(0, 0, 600, 200)

        ctx.beginPath()
        ctx.fillStyle = '#F9A520'
        ctx.moveTo(x1, 50) // 第一个点坐标
        ctx.lineTo(500, 150) // 顺时针，第二个点坐标
        ctx.lineTo(100, 150) // 顺时针，第三个点坐标
        ctx.fill() // connect and fill

        ctx.font = '12px bold 黑体'

        ctx.beginPath()
        ctx.fillStyle = '#000'
        ctx.fillText(startPoint.name + '，高程:' + startPoint.h, 80, ty1)

        ctx.beginPath()
        ctx.fillStyle = '#000'
        ctx.fillText(
          '高程差:' + (Number(endPoint.h) > Number(startPoint.h) ? endPoint.h - startPoint.h : startPoint.h - endPoint.h),
          tx2,
          100
        )

        ctx.beginPath()
        ctx.fillStyle = '#000'
        ctx.fillText(endPoint.name + '，高程:' + endPoint.h, 480, ty3)
      },
      //高程差分析结束
      //空间分析结束

      //获取面的树形数据
      listData2TreeData(listData) {
        if (listData.length > 0) {
          for (let i = 0; i < listData.length; i++) {
            listData[i].key = listData[i].id
            listData[i].title = listData[i].idName
            listData[i].scopedSlots = {
              title: 'title',
            }
          }
          let treeData = [
            {
              title: '全部区域',
              key: '000',
              children: listData,
            },
          ]
          return treeData
        }
        return []
      },
      // modalBox
      showModalBox() {
        let e = this.visible
        this.visible = !e
      },
      clearAllMapInteraction() {
        let interactions = this.map.getInteractions();
        let length = interactions.getLength();
        for (let i = 9; i < length; i++) {
          let interaction = interactions.item(9);
          if (interaction instanceof Select) {
            interaction.getFeatures().clear()
          }
          this.map.removeInteraction(interaction)
        }
        this.pipeNetworkEditingFeature = {}
      },
      startEditLine() {
        const that = this

        that.clearAllMapInteraction()
        let selectInteraction = new Select({
          style: STYLE_SELECTED_MODIFY
        })

        let modify = new Modify({
          style: STYLE_MODIFY,
          features: selectInteraction.getFeatures()
        })

        modify.on('modifyend', function (e) {
          for (let i = 0; i < e.features.getLength(); i++) {
            let feature = e.features.item(i);
            let featureObj = feature.feature
            let coordinates = feature.getGeometry().getCoordinates();
            let geom = '[' + coordinates.map(item => '[' + item + ']').join(',') + ']'
            featureObj.geom = geom
            that.pipeNetworkEditingFeature[feature.id] = featureObj
          }
        })

        let snap = new Snap({
          pixelTolerance: 5,
          source: that.lineVector.getSource()
        })

        that.map.addInteraction(selectInteraction);
        that.map.addInteraction(modify);
        that.map.addInteraction(snap);
      },
      cancelEditLine() {
        console.log('cancelEditLine')
        this.saveEditLine()
        this.clearAllMapInteraction()
      },
      saveEditLine() {
        console.log('saveEditLine')
        let keys = Object.keys(this.pipeNetworkEditingFeature)
        if (keys.length == 0) {
          this.$message.warn('没有需要保存的数据')
        } else {
          console.log(this.pipeNetworkEditingFeature)
          batchUpdateLine(this.pipeNetworkEditingFeature).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
              this.pipeNetworkEditingFeature = {}
            } else {
              this.$message.warn(res.message)
            }
          })
        }
      }
    },
  }
</script>
<style lang="scss" scoped>
  /* 图层控制 */
  .layercontrolDiv {
    position: absolute;
    top: 6px;
    right: 34px;
  }

  .layercontrolDiv .layercontrol {
    position: absolute;
    right: 5px;
    /* text-align: center; */
  }

  /* 图层控制 */
  /* 鹰眼样式 */
  .olmap .ol-overviewmap,
  .olmap .ol-overviewmap.ol-uncollapsible {
    bottom: 0;
    left: auto;
    right: 0;
    top: auto;
  }

  .olmap .ol-overviewmap:not(.ol-collapsed) {
    border: 1px solid black;
  }

  .olmap .ol-overviewmap .ol-overviewmap-map {
    border: none;
    width: 200px;
  }

  .olmap .ol-overviewmap .ol-overviewmap-box {
    border: 2px solid red;
  }

  .olmap .ol-overviewmap:not(.ol-collapsed) button {
    bottom: 1px;
    left: auto;
    right: 1px;
    top: auto;
  }

  .olmap .ol-overviewmap button {
    transform: rotate(180deg);
    -ms-transform: rotate(180deg);
    /* IE 9 */
    -moz-transform: rotate(180deg);
    /* Firefox */
    -webkit-transform: rotate(180deg);
    /* Safari 和 Chrome */
    -o-transform: rotate(180deg);
  }

  /* 鹰眼样式 */
  /*弹窗 */
  .ol-popup {
    /* display: none; */
    position: absolute;
    background-color: white;
    -moz-box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2);
    -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
    filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
    border: 1px solid #cccccc;
    top: -50px;
    left: 5px;
    min-width: 240px;
  }

  .ol-popup:after,
  .ol-popup:before {
    top: 40px;
    border: solid transparent;
    content: ' ';
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
    border-width: 10px;
    transform: rotate(90deg);
    margin-left: -20px;
  }

  .ol-popup:after {
    border-top-color: white;
  }

  .ol-popup:before {
    border-top-color: #cccccc;
  }

  .popup-title {
    font-weight: bold;
    border-bottom: 1px solid #cccccc;
    padding: 5px 12px;
  }

  .popup-content {
    padding: 5px 8px;
  }

  .ol-popup-closer {
    pointer-events: auto;
    text-decoration: none;
    position: absolute;
    top: 6px;
    right: 6px;
  }

  .ol-popup-closer:after {
    content: '✖';
  }

  /*弹窗 */
  /* 标注点 */
  .ol-overlaycontainer > *,
  .ol-overlaycontainer-stopevent > * {
    pointer-events: none;
  }

  /* 标注点 */
  /* 弹出菜单 */
  .modalBox {
    width: 200px;
    height: auto;
    margin-top: 20px;
    position: absolute;
    right: 0px;
    /* text-align: center; */
    background-color: #ffffff;
    border-radius: 5px;
  }

  /* v-enter 【这是一个时间点】 是进入之前，元素的起始状态，此时还没有开始进入 */
  /* v-leave-to 【这是一个时间点】 是动画离开之后，离开的终止状态，此时，元素 动画已经结束了 */
  .v-enter,
  .v-leave-to {
    opacity: 0;
    transform: translateX(150px);
  }

  /* v-enter-active 【入场动画的时间段】 */
  /* v-leave-active 【离场动画的时间段】 */
  .v-enter-active,
  .v-leave-active {
    transition: all 0.4s ease;
  }
</style>
